Reputation: 387677
The let
statement in ES2015 allows us to declare block scope variables, so that for example the following code does what we want:
let fs = [];
for (let i = 0; i < 3; i++) {
fs.push(() => i);
}
console.log(fs.map(f => f())); // 0, 1, 2
However, it does not seem to work in Firefox with the for…of
loop which iterates over iterable objects. Here, the block scope is ignored, and we get the same result as if we used var
instead:
fs = [];
let nums = [0, 1, 2];
for (let i of nums) {
fs.push(() => i);
}
console.log(fs.map(f => f())); // 2, 2, 2
Why is the behavior of let
not working here, and what’s internally so different about the for…of
loop that this breaks?
Upvotes: 4
Views: 98
Reputation: 387677
As others pointed out in the comments, this broken behavior seems to be specific to Firefox, and the code is working properly in other environments (e.g. V8/Node).
As such, I have created a bug report for it. I’ll update this answer as I learn something new from the Firefox team.
This bug has been fixed around August last year and has since landed in the central codebase. The fix is now included in the Firefox 51 release that had its final release on January 24th, 2017.
I’m using the Firefox Nightly preview versions and it has been working there properly for a while.
Upvotes: 2