Accessing arrays in loops

Hello everybody,

I’m currently learning loops, and this part got me puzzled :

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 don’t get how the “let i = 0” has to mean the 0 indexed in my array written earlier. (I’m sorry if I don’t make myself very clear, english is not my first language and when it gets technical its hard ahah)

Like why not use let i = [0] or let i = vacationSpots[0] ? How does the loop knows to pick the 0 as an index from an array and not as 0 being a number ?
And why doest it has to be vacationSpots[i] to log it and not just i ? (i being a variable I should be able to call it without the array no ? )

Thank you very much :slight_smile:

Hello!
The i variable does not refer to anything within the array vacationSpots. Rather, it is just assigned a number (starting at 0), which is incremented every time the loop loops. As you will have learnt in the previous lessons, vacationSpots[i] is an example of array indexing. Where, in this case, i is the index.

Thank you, it’s a bit more clear.
I’m just not sure how 0 refers to the array ? Maybe I’m thinking about this the wrong way, but since the loop concerns the array, it needs to be linked to it in some way no ?
For any loop it would always start with a 0 ?

The reason i starts at 0 is due to the declaration here:

This means i is now equal to 0.

This tells the loop to run as long as this condition is met. In this case, the condition is that i must be less than the length of the vacation Spots array.

This tells the loop what to do with the variable i. This means add one to i every time the loop loops.

The only way it is “linked” to the array is in the condition

And when you print out each value from the array:

console.log('I would love to visit ' + vacationSpots[i]);
                                       ^^^^^^^^^^^^^^^^^

0 does not refer to the array, it is just a number. But, when you use array indexing-here:

the 0 refers to the first element in the vacationSpots array

2 Likes

Ok I think I get it, thank you very much for breaking down all the explanation :slight_smile:

2 Likes