I don't understand how this certain code works inside of the loop

Hey all so this code here in the picture is confusing me right. So basically the outcome of this code if you run it is.

“I would love to visit Bali
I would love to visit Paris
I would love to visit Tulum”

This confuses me because inside of the loop at vacationSpots[i] I see that variable [i] in the brackets as vacationSpots[2] after the loop. because as the loop iterates through the length of vacation spots I think it will stop at ‘Tulum’ because its index number is 2. So I don’t see why it prints all 3 because the way I understand it should just print “I would love to visit Tulum” because the index number is just [2] and not [0, 1, 2] or is it?

I tried searching everywhere for the answer but I really found my first roadblock lol…

HALP and thank you in advance!!

Hi there, and welcome to the forums!

The function of a for loop is to use a set variable (usually i) to iterate a set number of times. In this case, i starts at 0, will loop to the first integer before vacationSpots.length (length is 3, so i goes to 2) and increments by 1 each time. Therefore it will set i = 0, execute the code block, then increment by 1, execute the block again and so on.

So the reason it prints all three is because the first time it runs the index is 0, so it gets the first element. The next iteration i has a value of 1, and so this gets the index 1 and finally rests on i = 2, getting that with an index of 2. At any one time, i only takes one integer value, but the beauty of the for loop is that it runs the code each time. Since the console.log() is inside the loop, this will be run each time and the value, which changes, will be printed each time.

1 Like

Oh gosh! that also explains to me how loops would be useful as well lol. Well, thank you for that answer it was very helpful.