0

Here's the code:

var john = ['John', 'Smith', 1990, 'teacher', false, 'blue'];

for (var i = john.length - 1; i >= 0; i-- ) {
    console.log(john[i]);
}

I am trying to understand why use -1 in the declaration instead of using:

for(var i = john.length; i>-1; i--){
    console.log(john[i]);
}

Which to me makes more sense because the index i would have the value of the array which is 6 but since arrays starts with 0, it will not execute index 0 and therefore, for it to be executed, the condition has to be greater than -1.

Sorry I'm sort of new to programming.

5
  • The highest index of an array of length 3 is 2: 0,1,2. Commented Jan 17, 2020 at 22:15
  • Try running both versions of the code yourself and see what happens. Commented Jan 17, 2020 at 22:16
  • @FelixKling I am aware of that but why use john.length -1? I did run the code and there was an undefined value before it executes the array. Why is that so? Commented Jan 17, 2020 at 22:51
  • Because if i = john.length, then i = 6 (in your example) and john[6] is undefined because the highest index is 5 (john[5] returns 'blue'). Simple reproduction: console.log([1,2,3][2]); console.log([1,2,3][3]);. Commented Jan 17, 2020 at 23:23
  • @FelixKling Thank you very much. Now that makes sense. Commented Jan 17, 2020 at 23:38

2 Answers 2

1

In the first iteration, i would be john.length, so the reference to john[i] would be past the end of the array. Array indexes go from 0 to length - 1.

Of course i > -1 is just as good as i >= 0 if you prefer it.

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

Comments

1

For looping backwards, you might use a different pattern, which uses the truthy/falsy characteristic of a number in a condition.

This approach uses a check for truthiness and supports zero based indices of arrays.

var john = ['John', 'Smith', 1990, 'teacher', false, 'blue'],
    i = john.length;

while (i--) {
    console.log(john[i]);
}

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.