Iteration with JavaScript For Loops

Iteration with JavaScript For Loops
0

#1

Quoting the example:
“var ourArray = [];
for (var i = 0; i < 5; i++) {
ourArray.push(i);
}
ourArray will now contain [0,1,2,3,4].”

I don’t understand why there is a 0 in the final array. If the variable i start from 0, we check the condition, it’s true, and it does i++ which means i = i + 1, which is 0 = 0 + 1 which is 1 no? So at this point, i should be already = 1, so when execute the code ourArray.push(i); it should be pushing as the first element of the array 1. Thank you.


#2

The final part of a for loop (in this case i++) happens at the end of each iteration of the loop.


#3

That is a good question.

The increment part does not happen until after the loop cycles. i =0 until the end of the first cycle and then becomes 1. If it did not work that way you could never use i = 0 for calculations, etc.

There’s more here