Trying to Learn Javascript Trying to Learn Javascript - 5 months ago 11
Javascript Question

Basic For Loop Logic Doesn't make sense to me

I've been trying to learn Javascript for the longest time, and it is kind of frustrating. I'm back to learning the basics again, and I was playing around with these

for
loops and arrays below.

Can someone please explain why the output of this code is
[1,2,3,4,5]
and not
[6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25]
?

var game1 = new Array();
for(i = 25; i > "love is like a river".length; i = i - 1) {
console.log(game1.push(i));
}

Answer

The "love is like a river".length is 20. So the loop is equivalent to this:

for(i = 25; i>20; i=i-1){

}

That being said, you have 5 calls of the console.log passing to it the following arguments one at each for step:

game1.push(25)
game1.push(24)
game1.push(23)
game1.push(22)
game1.push(21)

Not knowing exactly what game1.push does, it's hard to tell. However, supposing that game1 is an array, you would get at each push the new length of the array.

According to MDN:

The push() method adds one or more elements to the end of an array and returns the new length of the array.