0

for loop and setTimeout with VAR

The Code is:

for (var i = 0; i < 5; i++) {
  setTimeout(() => {
    console.log('The index of this number is: ' + i);
  }, 0);
}

And the output is 5 times the line

The index of this number is: 5

for loop and setTimeout with LET

The Code is:

for (let i = 0; i < 5; i++) {
  setTimeout(() => {
    console.log('The index of this number is: ' + i);
  }, 0);
}

The output is:

The index of this number is: 1
The index of this number is: 2
The index of this number is: 3
The index of this number is: 4
The index of this number is: 5

Why the output is different ? Why does this work like this ?

yakov
  • 1
  • 1
  • Here you can find info on what are the crucial differences between `let` and `var`. https://stackoverflow.com/questions/762011/whats-the-difference-between-using-let-and-var – Oris Sin Mar 07 '22 at 09:34
  • Have you read the duplicate linked on top of your question? TL;DR: the `for .. let` syntax was created more or less specifically to deal with this rather common, somewhat surprising pitfall. – deceze Mar 07 '22 at 10:04

0 Answers0