1

here's the example:

var a = [];
for (let i = 0; i < 10; i++) {
    a[i] = function () {
    console.log(i);
    };
}
a[6](); //outputs 6

the problem is,in this case,variable declarated by let is only accessible in "for" block,so after the loops,how does the function a[6] obtain the value of i?

I translate this es6 sourse code into es5 by Bable,which output the code below:

"use strict";
var a = [];
var _loop = function _loop(i) {
    a[i] = function () {
        console.log(i);
    };
};
for (var i = 0; i < 10; i++) {
    _loop(i);
}
a[6]();

Bable create a new function _loop.So on each iteration,the i variable will be copyed and passed into the function _loop, which is a closure.And i variable is accessible after the loops.it seems like let in es6 just simplify and immitate what closure in es5 do.

Tommy
  • 11
  • 1
  • "*how does the function a[6] obtain the value of i?*" - by closure, as always. It just closes over a (block) scope that is not accessible outside of the loop. – Bergi Sep 02 '16 at 05:25
  • @AndrewL.: Block scoping means that it's not accessible outside of the block. "after the for loop" is ambiguous. – Bergi Sep 02 '16 at 05:28
  • thanks,but it's a little confusing.the other block scoping in es6 is function block,once the function call finished,the variable declared in function will be destroied.But `let` don't like this. – Tommy Sep 02 '16 at 05:33
  • No, function scopes are something different than block scopes. But not even in function scopes variables are destroyed when they are still closed over, as your ES5 example demonstrates. – Bergi Sep 02 '16 at 05:42

0 Answers0