I have a question about how the let
scope work in a for
loop, regarding the following examples.
for(let i=0;i<5;i++){
setTimeout(()=>{
console.log(i);
},1000)
}
// will print out 0,1,2,3,4
for(var j=0;j<5;j++){
setTimeout(()=>{
console.log(j);
},0)
}
// will print out 5,5,5,5,5
I know the difference between var
and let
. The var
has a function scope and the let
has a block scope.
For the let
one, though the i
is inside the for
loop, the console.log(i)
always take in the same variable i
. The variable i
is updated in each iteration. So when the setTimeout
callback functions are executed, they have the same i
, and they should print the same number, which is 5
here.
The var
and let
have different scope, but both are updated in each iteration, and both variables are logged at the end. Shouldn't they have the same result?