For Loops and Indexes


#1

I’ve gone back in my notes trying to find where indexes and start conditions where introduced and explaining how they are written out. In exercise 3/8 learning For Loops, in the example given it looks like:

let animals = [“Grizzly Bear”, “Sloth”, “Sea Lion”];

for (let animalIndex = 0; animalIndex < animals.length; animalIndex++) {
console.log(animals[animalIndex]);

When I was working on my own For Loop as prompted, I was writing out my start condition exactly as the variable used in my array. The variable for the array is “vacationSpots”, and I was writing my start condition out as “vacationSpotsIndex”, but it was wrong until I dropped the “s”. Why is the “s” dropped?


#2

No real reason other than to make it singular, the same as the earlier example…

animals        =>  animalIndex

vacationSpots  =>  vacationSpotIndex

#3

So it’s not actually required to be singular for it to work? If I wrote it out the way I did in my own code in the future, it would still work?


#4

Never mind. I understand what it means now. It’s not the same thing as the variable used for the array. Thank you.


#5

Yes, it will. Variable names are meant for readers, not the computer so they are arbitrarily chosen by the author. The best variable names are the ones that a reader will understand immediately once viewed in context.

In loops it is common to see an object with a pluralized name, and the iterator in a loop will be the singular.

for (animal of animals) {}

In the above, animals will be the array, animal will the individual value retrieved from the array during iteration.


#6

Okay, I don’t recall it explaining that in the exercise, but now I understand. Thank you.


#7

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