Help explain the math behind looping through arrays

Looping through Arrays page 5 of 10

I’m in the Looping through Arrays section of the free JavaScript course and on page 5 it supplies this code as an example:

const animals = ['Grizzly Bear', 'Sloth', 'Sea Lion'];
for (let i = 0; i < animals.length; i++){
  console.log(animals[i]);
}

which gives the output:
Grizzly Bear
Sloth
Sea Lion

Then it basically asks you to do the same thing but with different strings in the Array

const vacationSpots = ['Bali', 'Paris', 'Tulum'];

// Write your code below
for (let i = 0; i < vacationSpots.length; i++) {
  console.log('I would love to visit ' + vacationSpots[i]);
}

I was able to write the code correctly by just copying the given example and replacing the variable name, but I don’t really understand the math behind it.
I read this in the cheatsheet section.
" An array’s length can be evaluated with the .length property. This is extremely helpful for looping through arrays, as the .length of the array can be used as the stopping condition in the loop."

but I still don’t entirely understand the math behind what all is going on here. Could someone please take the time to go through the each the initialization, stopping condition, and iteration statement and explain exactly what is happening at each point and why it leads to the output of each string in the array?

Hi.
The for loop repeats whats inside the curly brackets for as often as you tell it to inside the round brackets.

In the first part of the condition ‘let i = 0;’ you initialise a variable and set it to the value where it should start the counting from.

In the second part of the condition ‘i < vacationSpots.length;’ you tell your function, when it should stop counting: When it reached the value 2 (vacationSpots.length is 3 for the three spots stored in the array; i < 3 = 2).

In the third part of the condition ‘i++’ you count up one by one ( i++ is the short hand for the reassigning i = i + 1). Every time, the function is running, it is counting up by one.

In the first round, i = 0. With vacationSpots[i] (vacationSpot[0]), you get the first item of the array (‘Bali’). In the second round, i = 1 (vacationSpot[1] = ‘Paris’) and so on.

Hope that helps.

2 Likes

That cleared it up completely. thank you

1 Like