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?
4 Answers 4
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
2 Comments
(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', thenidecremented to 1 and output will beI would love to visit New York' & finally 0 and output will be I would love to visit Paris
1 Comment
In addition
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]);
}
1 Comment
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).
i=3, then it'll try to get the 4th item of the array, as arrays are 0-indexed. Since the length is 1-indexed (starts at 1), you have to do- 1to make sure it is in range of the array.