JavaScript – variable incremented in for loop issue

When you declare a variable in a loop statement, it stores the variable in the same scope as the loop. Loops increment (i++) at the end of the loop, then check the condition (i < 5) to see if they should repeat. After the loop, the variable i still exists. See the snippet below for a play-by play.

Also, you should use the var keyword when declaring i, otherwise, the variable is stored in the global scope (which is bad practice).

//variable i is captured here (with the var keyword)

for(var i = 1; i < 5; i++) {
  //for the fourth iteration, i === 4
  
  //so it prints 4.
  document.write(i);
  
  
  //i++ happens right now, so i now is 5.
  //then the loop checks the condition to see if it
  //should continue. i isn't less than 5, so the loop breaks.
}

//and the value of i is still 5. so this prints 5.
document.write('</br>' + i);

Leave a Comment