Why does this code work? Whats wrong with my reasoning?


#1

For Loops

Hi, just a quick question. I passed the exercise but don't understand why the code works.

var vacationSpots = ["Amsterdam", "Galapagos", "Iceland"];

for (var i = 0; i < vacationSpots.length; i++) {
 console.log("I would love to visit " + vacationSpots[i]);
}

The condition for the loop to stop is:

i < vacationSpots.length;

The first time the loop is run i is already less than vacationSpots.length because i = 0 and vacationSpots.length = 3

The second time it is i = 1 thanks to i++ and so on until it gets to i = 3 in which case it stops looping and should stop looping. But in my mind 3 is bigger than vacationSpots.length so the stop condition shouldn't be met there.

Whats wrong in my thinking? Is the for loop counting down instead of up?


#2

Discovered my own mistake. Apparently i < vacationSpots.length doesnt tell the loop when to stop, it tells the loop when it is allowed to loop again. I had it on backwards.


#3

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.