function func2() {
for (let i = 0; i < 3; i++) {
setTimeout(() => console.log(i), 2000);
}
}
func2();
Due to closure
, the console.log
statement should remember its outer lexical environment, which is first setTimeout
and then the for loop. Since i
is not available in the setTimeout
context, it looks in the execution context of the for loop, and searches for the value of i
there.
Now, that value, after 2 seconds, should have been 3 for all three executions of console.log
. But it displays the output as:
0
1
2