2

Curious about why i becomes 5 in the end?

for (var i = 0; i < 5; i++) {
  console.log('A: ', i);
}
console.log('B: ', i);
Alessio Cantarella
  • 5,077
  • 3
  • 27
  • 34
  • `i = 4` -> `i < 5 === true` -> `console.log('A: ', i);` -> `i++` -> `i = 5` -> `i < 5 === false` -> end loop. – VLAZ Jun 23 '20 at 09:09
  • var i gets hoisted. It's equivalent to var i; for(i=0;i<5;i++) console.log(i); console.log(i) – user120242 Jun 23 '20 at 09:09
  • because at end it becames 5 and the condition becomes false and it breaks and console.log B where I = 5 – xMayank Jun 23 '20 at 09:10
  • @NinaScholz How do you guys find these dupes? Makes me feel like I don't know how to use Google anymore – user120242 Jun 23 '20 at 09:12

1 Answers1

3

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.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335