Consider the following code:
const captured = [];
for (var i = 0; i < 2; ++i) {
captured.push(() => console.log(i));
}
for (let x = 0; x < 2; ++x) {
captured.push(() => console.log(x));
}
captured.forEach(v => v());
This gives the above output in the snippet.
In both cases, we effectively have a loop variable that exists outside of the scope of the loop body, and in both cases that variable is being mutated.
The only way I can explain this output is if the let
declared loop variable (block-scoped) is "magically" copied when it is captured.
Did I get this right?