Loops 4/7


#1
var vacationSpots = ['a', 'b', 'c'];
for (var i=vacationSpots.length -1; i>=0; i--){
  console.log('I would like to visit ' + vacationSpots[i]);
}

Why do I use >=0 instead of =0? Wouldn’t >=0 stop the loop from running? Also why do I need to -1 when running the loop backwards but no -1 when running the loop forwards?


#2

We use an inequality so that the condition may be true for a range of values, not just a singular value. The loop will run until that condition is not met.

The indices 2, 1 and 0 meet this condition, while -1 will not, at which point the loop ends.


#3

Oh ok, I got yea now! So why do you not use -1 when running the loop forwards but it is a necessity while backwards? Does the computer not account for the zero index? (like it takes the length 3 and runs it backwards to 0 essentially making it 4? and that’s why you subtract the 1?)


#4

The 1 is subtracted because there is no index at array.length, but array.length minus 1.

array.length == 3

indices at 0, 1, 2

We cannot end the loop until after zero when counting down, so that the final index is reached.


#5

Ohh k I fully understand it now! Thank you mtf!


#6

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