0

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?

spender
  • 117,338
  • 33
  • 229
  • 351
  • It's not copied, it's a *different variable* to begin with. One scoped to only that particular iteration. – deceze Sep 18 '20 at 10:05
  • @deceze So, how does it get mutated? e.g. `++x`... Or does it not? Something magical is happening here that your comment above doesn't address. – spender Sep 18 '20 at 10:06
  • See https://stackoverflow.com/a/30900289/476. In a nutshell, it somewhat acts like having an additional `let x = x` inside the loop body (though that obviously is too simplified and doesn't work at a Javascript level)… – deceze Sep 18 '20 at 10:10
  • @deceze You beauty. That's what I was looking for. Thx. – spender Sep 18 '20 at 10:11

0 Answers0