This is the correct behavior as per specification. The behavior with var and let is defined as different.
See the specification at https://people.mozilla.org/~jorendorff/es6-draft.html#sec-forbodyevaluation . Accordingly, the relevant concepts that make a function declared inside a loop closed at the current value of the loop index with a limited block are called “bindings for each iteration” and “environment for each iteration”.
Babel processes it correctly, generating the following code:
var a = []; var _loop = function (i) { a[i] = function () { console.log(i); }; }; for (var i = 0; i < 10; i++) { _loop(i); }
This implements the semantics of for (let , isolating the contents of the for loop in a separate function parameterized by the index. Therefore, the function no longer closes by the index of the for loop, and i processed separately in each created function. Thus, the answer is 6.
Traceur does not give the correct result. This gives 10.
So, the famous question that was asked 100 times on SO about why my function declared in the loop and closing the index index using the "wrong" value of the loop index is no longer being requested?
The question is a little more nuanced, which simply proclaims that "of course let is a block area." We know that. For example, we get how it works in the if block. But what happens here is a bit of a twist on block coverage in a for context hitherto unknown to many people, including me. This is a variable that actually declared outside the "block" (if you consider the block as the body of the for statement), but has a separate existence inside , each iteration of the loop.
See https://github.com/babel/babel/issues/1078 for more details.
user663031
source share