I’m trying to understand the difference in behavior between let and var inside a for loop, especially when used with setTimeout.
Here’s a simple example:
for (var i = 0; i < 3; i++) {
setTimeout(() => console.log(i), 1000);
}
// Output: 3, 3, 3
for (let i = 0; i < 3; i++) {
setTimeout(() => console.log(i), 1000);
}
// Output: 0, 1, 2
I tried using both var and let inside a for loop with setTimeout, expecting them to behave similarly and print numbers 0 to 2 after 1 second. However, I noticed that:
- With let, the output is: 0, 1, 2
- With var, the output is: 3, 3, 3
This behavior confused me, as I thought both would just loop from 0 to 2 and print each value.
I now understand that scoping might be affecting it, but I want to know why exactly this happens and how closures are involved in this behavior.
let, the declaration applies to theforloop context only; outside the loop the variable is not defined.varversion is essentiallyvar i; for (i in 0..2) { do something later } .. later { print i }whileletis estentiallyfor (i in 0..2) { let index = i; { do something with this index } .. later { print that index }- so withvarit runs the loop first, meaning the print is for the current value of the outeri(ie 3)letscoping to the loop is what makes it actually work as expected.