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
You have used let which is block scoped so there will be separate i for each for loop iteration.
1) If you want to output consective 3 so you can declare i outside of for-loop, then there will be only single i with the value 3.
function func2() {
let i;
for (i = 0; i < 3; i++) {
setTimeout(() => console.log(i), 2000);
}
}
func2();
2) If you want same lexical scope then you can also use var here,
varis function scoped, So there will only be onei
function func2() {
for (var i = 0; i < 3; i++) {
setTimeout(() => console.log(i), 2000);
}
}
func2();