@ jester070993
Even though the for loop is written on one line you have to think of it like this (they just did that for convenience):
-
make your variable (or don’t if you already have one) : Only do this once
-
check the condition
a- if the condition is false stop
b-if the condition is true do the stuff in the scope
-
increment your counter, repeat
So the increment is actually happening at the end of your loop even though it is not positioned there.
Some languages you do put the increment a the end of the loop scope, but this is tidy once you get used to it.
5 is not < than 5. Change the condition check to <= if you want the array to be 0,1,2,3,4,5
so the for loop:
creates i, and sets it equal to 0
tests 0 is less than 5, here 0 is i
puts 0 in the array, using push
increments i to 1 (i++)
tests 1 < 5, here 1 is i
puts 1 in the array, using push
increments to 2 (i++)
…same for 2, 3 and 4 (where those numbers are the value of i)
tests 5 < 5, here 5 is i
breaks the for loop
the array is [0,1,2,3,4]
As I said change to <= 5 as the condition check and you will get [0,1,2,3,4,5]
Play around with it a little, like
for (i = 4, i >= 0, i--)
this should reverse your array.
Its similar to a Do-While loop in a single line.
Beware of endless loops . . . infinity awaits.
As a testing piece you can always say if( i === 10) {break}
you can combine with OR (||) to bracket your loop range just in case on future loops
if( i === 10 || i === -10) {break}
in this manner you loop for whatever reason in more complex code will not runaway on i.
not likely to happen here but once you get more complex . . . . (think recursion) things can get a little troublesome.
-WWC