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.
3is2:0,1,2.i = john.length, theni = 6(in your example) andjohn[6]isundefinedbecause the highest index is5(john[5]returns'blue'). Simple reproduction:console.log([1,2,3][2]); console.log([1,2,3][3]);.