0

I can't figure out the output of the following two loops. The only difference I notice is that the former use var and assigns a global scope and later create a local scope using const.

for (var i = 0; i < 3; i++) {
  setTimeout(() => console.log(i), 1);
}

for (let i = 0; i < 3; i++) {
  setTimeout(() => console.log(i), 1);
}

the output is 3 3 3 and 0 1 2. According to my shallow knowledge, the first loop has to output 0 1 2.

If I print the value of i in the first loop.

for (var i = 0; i < 3; i++) {
  console.log(i);
  setTimeout(() => console.log(i), 1);
}

the output printed in the console by first console.log(i) is 0 1 2. While in the one wrapped within setTimeout vary.

Why?

Mir Stephen
  • 1,758
  • 4
  • 23
  • 54

1 Answers1

0

var gets hoisted into the global scope, so when setTimeout is called it logs out whatever the value of i is when it is called, which would be 3 as the for loop has set i to 3 on its last iteration. Whereas let is scoped to the for loop and closes over the value of i on each iteration, thus printing 0 1 2.

ourmaninamsterdam
  • 1,915
  • 15
  • 11