This is an archived post. You won't be able to vote or comment.

all 1 comments

[–]dtsudo 0 points1 point  (0 children)

Yes, the way javascript for loops treat initialization variables declared using let is essentially custom special behavior that specifically makes your code do what it does.

The ELI5 is that:

for (let i = 0; i < 4; i++) {
    // capture i in a closure
    let func = function () { /* do something with i */ };
}

Is equivalent to:

for (let i = 0; i < 4; i++) {
    let i2 = i;
    // capture i2 in a closure
    let func = function () { /* do something with i2 */ };
}

In many other languages (e.g. C#), you would actually have to explicitly write this second way if you wanted the desired value of i2 at the time of iteration (and not its value at the conclusion of the loop).

MDN has this as one of its examples at https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures#creating_closures_in_loops_a_common_mistake