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?