In below snippet, the function passed to setTimeout
forms a closure with the variable i
which is present in the script
scope. So the function contains a reference to variable i
. The value of i
is updated to 5 before i
is logged to console. And the output is: 5 5 5 5 5
(with newlines)
script.js
:
let i;
for (i = 0; i < 5; ++i) {
setTimeout(() => {
console.log(i);
}, i * 1000);
}
The above part is clear to me. But when I declare variable i
inside for
loop, then i
is block scoped to the for
loop.
for (let i = 0; i < 5; ++i) {
setTimeout(() => {
console.log(i);
}, i * 1000);
}
In this code snippet, I expect the output to be same as output of first snippet, because the closure contains reference to the variable i
and the value at that reference should be updated to 5 before the value is logged to console. But the actual output is: 0 1 2 3 4
(with newlines)
The question is, why the code in second snippet behaves this way?
It it because:
- A new copy of variable
i
is created in memory for each iteration offor
loop and previous copy is garbage collected? I'm not sure how memory management works for loops. - Instead of storing reference of
i
, the value ofi
is stored in closure? I don't think this is the case. - Anything else?
Please help to clarify. Thanks!