Reputation: 11
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.
Upvotes: 0
Views: 66
Reputation: 386550
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]);
}
Upvotes: 1
Reputation: 413702
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.
Upvotes: 1