Unexpected Result

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

Why is the result of i, 3? I don’t see it being assinged anywhere.

This line sets and then modifies the value of i. Are you familiar with loops?

But why would i = 3? It starts at 0 and goes through until i = 3 and stops. I understand why I get the numArray ([-0, 1, 2]), but not 3.

When the value of i is 2, the condition is true and loop will be executed. Now i will be incremented to 3 and condition becomes false. That’s why i is 3.

Loops occur in three steps

  1. Initalize (separate step)

  2. Check loop exit condition (i < 3)

  3. Execute loop body (numArray.push(i))

  4. Increment iterator (i++)

Your loop does not stop until i < 3 is false, which is when i == 3.