Javascript - Question regarding Set Timeout

Viewed 54

As per my understanding, the below function should print 5 five times because of hoisting. But instead, it prints 6 five times.

Question is, how come it prints 6 when the loop's limit is <=5?

function () {
  for ( var i = 1; i <= 5; i++) {
    setTimeout( function() {
      console.log(i); //  this should print '5' five times 
    }, i * 1000)
  }
}
3 Answers

It prints 6 because that’s the value of i when the loop exits.

Consider the flow at the end of the loop’s run, when i is 4:

  • Is i <= 5? Yes.
  • execute the body
  • increment i to 5
  • Is i <= 5? Yes.
  • execute the body
  • increment i to 6
  • Is i <= 5? No.
  • exit the loop

The for loop stops after the i++ occurs which meets the condition for exiting (i.e. 6 > 5) - at that point, the value of i has incremented to 6 already and about a second later the value of i is printed

It is because of the increment you apply sol =>

function num() {
  for ( var i = 1; i <= 4; i++) {
    setTimeout( function() {
      console.log(i); //  this should print '5' five times 
    }, i * 1000)
  }
}
num()
Related