-1

I have this code.


for (var i = 1; i <= 5; i++) {
    setTimeout(function () {
        console.log(i);
    }, 1000);
}

I don't understand the output from this lines of code: The output in the console is number 6,and it says that is repeated five times. If i use the let keyword for "i" then i get the output that i expect, 1,2,3,4,5 after one second Why is that ?

Trajce12
  • 261
  • 2
  • 16

2 Answers2

0

var has scoping issues and that's why let was introduced.

In your for loop you are defining i, but actually it's stuck to the global scope, and after 1 second, the for loop would actually be done, and when the setTimeout callback is fired, i would have already reached 6 and it's read from the global scope.

In a nutshell, because i is stuck to the upper scope of for, each iteration modifies the calue of i and doesn't create another i.

If you change var to let, the issue is resolved.

rksh1997
  • 1,103
  • 7
  • 17
0

setTimeout is async hence will execute after the loop is done, that s why you have i=6, put it in a self invoking function to retain the value of i or use let instead of var in your loop

for (var i = 1; i <= 5; i++) {
  ((i) => setTimeout(function() {
    console.log(i);
  }, 1000))(i)
}

for (let i = 1; i <= 5; i++) {
    setTimeout(function () {
        console.log(i);
    }, 1000);
}
EugenSunic
  • 13,162
  • 13
  • 64
  • 86