for(var i = 0; i < 5; i++){
setTimeout(() => console.log(i)
}
for(let i = 0; i < 5; i++){
setTimeout(() => console.log(i)
}
Why the loop with let return 0,1,2,3,4 but loop with var return 5,5,5,5,5 ?
for(var i = 0; i < 5; i++){
setTimeout(() => console.log(i)
}
for(let i = 0; i < 5; i++){
setTimeout(() => console.log(i)
}
Why the loop with let return 0,1,2,3,4 but loop with var return 5,5,5,5,5 ?
This is because of hoisting. Declaring a variable with var in your for loop doesn’t limit its scope to just that block of code like it would using let. Since its existence extends beyond that for loop, when the value is evaluated by the setTimeout() callback, you get the last value it was set to. (it gets set to 5, which is why the for loop stops)
for (var val = 0; val < 5; val++) {
setTimeout(() => console.log(i)
}
if (val === 5) {
console.log('I can still see the value');
}
You can see the same behavior while using let if you’ve already declared the variable before using it in your for loop.
let i;
for (i = 0; i < 5; i++) {
setTimeout(() => console.log(i)
}
Now it would behave the same way as the var for loop did.