Local variable to global variable in JS for loop, value changed after loop ends

Viewed 47

Curious about why i becomes 5 in the end?

for (var i = 0; i < 5; i++) {
  console.log('A: ', i);
}
console.log('B: ', i);

1 Answers

i++ increases the value of i at the end of each loop.

The loop goes round until the condition (that i is 4 or less) isn't true.

When i is 5, that is the first time the condition isn't true.

Related