Trouble with For loop logic


#1

Intro to For loops.

I'm having a little trouble understanding the logic behind this code, and I was wondering if anyone could help me. First of all, here's the code in question:

var vacationSpots = ["Hawaii", "New York", "Sea of Tranquility"]
for (var i =  vacationSpots.length - 1; i >= 0; i--) {
  console.log("I would love to visit " + vacationSpots[i]);
}

Now, as I understand it, the start condition has a value of 2. The stop condition tells the loop to stop running when i has a value greater than or equal to zero, and the iteration deducts 1 from i every time the loop executes. The thing I don't get is that, if the stop condition is basically telling Javascript "Stop running this loop as soon as i is greater than or equal to zero", why does the loop run at all? It already has a value greater than or equal to zero at the very beginning.

The code itself works absolutely fine, but I just can't figure out why it works. Any help would be gratefully appreciated. Cheers :slight_smile:


#2

With

you have created an Array.

With this Array you have 3 Elements / Items --> (vacationSpots.length)

An Array is accessed using the Index in the so-called bracket-Notation

Now the confusing part....
The Index-count starts at =zero=
thus with vacationSpots[0] you get =access= to the 1st-Element which is "Hawaii"

==========================================================
An other example

With
var numbers = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]
you created a numbers Array.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array

To get the 1st Array-Element of the numbers Array
you use
numbers[0]

and to get all Elements with a for-loop you will have to start
at Element-zero
like

for (var x = 0; x < numbers.length ; x++ ) {
   console.log( number[x] );
}

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for


#3

for (var i =  vacationSpots.length - 1; i >= 0; i--)
-------------------------------------------------------
Loop1
Step1  i = 3 -1
Step2  i >= 0 is true
Step3  execute console.log() Method using =index=-2 [2]
Step4  i = i -1 ---> i = 1
-------------------------------------------------------
Loop2
Step1  i >= 0 is true
Step2  execute console.log() Method using =index=-1 [1]
Step3  i = i -1 ---> i = 0
-------------------------------------------------------
Loop3
Step1  i >= 0 is true
Step2  execute console.log() Method using =index=-0 [0]
Step3  i = i -1 ---> i = -1
-------------------------------------------------------
Loop4
Step1  i >= 0 is false =====> FOR-loop EXIT

#4

That's really helpful, thanks!


#5

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