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.
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
Initalize (separate step)
Check loop exit condition (i < 3)
Execute loop body (numArray.push(i))
Increment iterator (i++)
Your loop does not stop until i < 3 is false, which is when i == 3.