1
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?

1
  • If you would start at 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 - 1 to make sure it is in range of the array. Commented May 29, 2017 at 15:47

4 Answers 4

2

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

Sign up to request clarification or add additional context in comments.

2 Comments

Just to add to that, this applies whether you're looping forwards or backwards.
i get it now. sorry im a newbie in javascript.well thank you so much for your help :)
1

(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

Thank you very much bro! i get it now :)
1

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

You're right, I didn't confuse it, I just had a brain fart. I'll delete the comment. Thanks for putting up with my inebriation ;)
0

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).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.