Reputation: 17
var vacationSpots = ['Paris', 'New York', 'Barcelona'];
for(var i = vacationSpots.length - 1; i >= 0; i--) {
console.log('I would love to visit ' + vacationSpots[i]);
}
Hello guys,my question is whats the logic in "-1" in the for loop to be reverse.i get it that for(var i = vacationSpots.length; i >= 0; i--) {
helps you running Backwards. but what's the use of -1 in printing the items in array backwards?
Upvotes: 1
Views: 93
Reputation: 171679
Very simple ... array length is a count but indexing is zero based.
So if myArray
length is 5 , the last index is 4 and myArray[5]
doesn't exist.
So when iterating arrays by index you can't overshoot the last index which is length-1
Upvotes: 2
Reputation: 12854
There is another way for reverse loop (without '-1'):
var vacationSpots = ['Paris', 'New York', 'Barcelona'];
for (var i = vacationSpots.length; i--;) {
console.log('I would love to visit ' + vacationSpots[i]);
}
Upvotes: 1
Reputation: 945
Index Array in Javascript start at 0, so you have vacationSpots[0]=Paris, vacationSpots[1]=New York, vacationSpots[2]=Barcelona. vacationSpots.length is 3 so you need to print 0 1 2. In general index goes from 0 to n-1, where n = number of items (length).
Upvotes: 0
Reputation: 50291
(vacationSpots.length)
is the length of the array but array index start from 0
. So here the i
value is set to 2 that mean the loop will execute 3 times
Initially i
will set to 2, so vacationSpots[2]
will be I would love to visit Barcelona', then
idecremented to 1 and output will be
I would love to visit New York' & finally 0 and output will be I would love to visit Paris
Upvotes: 1