Consider the following code snippet:
for (let i = 0; i < 5; i++) {
i+=1;
setTimeout(() => console.log(i), 100);
}
console.log('after for loop');
If let i
were creating a new block scope variable with each iteration, I would expect it to output:
1
2
3
4
5
because, being a new block scope variable, i+=1;
would only make changes to my local copy of i
. Also, if i
was a new block scope variable, that would explain why the setTimeout
callback doesn't log "6" 3 times (as it does if let i
is changed to var i
).
In case it helps, here is what I'm imagining it would be doing under the hood if it were creating a new block scope variable for each iteration:
for (let I = 0; I < 5; I++) {
let i = I;
i+=1;
setTimeout(() => console.log(i), 100);
}
console.log('after for loop');
However, the top snippet actually outputs:
1
3
5
which would make sense if i
were shared between all iterations except if i
were shared between all iterations why would the setTimeout
callback not print the same number 3 times?
In short my question is:
Why, in the top snippet, is i+=1;
both updating the loop variable as if i
in i+=1;
is not a local copy for each iteration and also behaving in the setTimeout
callback as if i
is a local copy for each iteration.