0

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.

4
  • it has everything to do with scoping. When you use let, the declaration applies to the for loop context only; outside the loop the variable is not defined. Commented Jun 25 at 15:34
  • tl;dr the var version is essentially var i; for (i in 0..2) { do something later } .. later { print i } while let is estentially for (i in 0..2) { let index = i; { do something with this index } .. later { print that index } - so with var it runs the loop first, meaning the print is for the current value of the outer i (ie 3) Commented Jun 25 at 15:49
  • 1
    @mankowitz 1. both are hoisted 2. even then your explanation is backwards, because if you mean "hoisting" as in out of the block scope, then this hoisting will be the problem. let scoping to the loop is what makes it actually work as expected. Commented Jun 25 at 15:50
  • @VLAZ - You're right. I think my initial comment is very misleading, I was trying to say scope, but it came out backwards. I'll delete that comment, but leave this one so that people can still read your explanation. Commented Jun 25 at 17:18

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.