Iteration / Recursion

Why is ‘i’ = 3 ?

var numArray = [];
for (var i = 0; i < 3; i++) {
  numArray.push(i);
}
console.log(numArray);
console.log(i);

Because a loop works like this:

for (A; B; C) {D}

image

C, which is the augmentation of i in this case, always happen before determining if the loop ends or not.
So, at one point i becomes 3, i < 3 is false and the loop ends

It might be worth asking what you expected it to be?

If you think about it, the fact that 0 is the first number pushed should be no more or less surprising than i being 3

for (initialization; condition; afterthought)
  statement

i is initialized to 0
0 is less than 3
0 is pushed to the array
i is increment to 1

1 is less than 3
1 is pushed to the array
i is increment to 2

2 is less than 3
2 is pushed to the array
i is increment to 3

3 is not less than 3
loop exits

i is a var so it is accessible after the loop exits. If it was a let is would be out of scope and a reference error would be thrown.

So i is 3 because after the last iteration where the condition is no longer met i was equal to 3 ?

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.