1

Can someone explain why the first iteration of a reverse for-loop logs undefined?

var arr = [1, 2, 3, 4, 5, 6, 7, 8]

for (var i = arr.length; i > -1; i--) {
  console.log(arr[i]);
}
Ivar
  • 6,138
  • 12
  • 49
  • 61
  • 3
    var i = arr.length-1; – Cruiser Dec 21 '16 at 16:05
  • 1
    just for the sake of adding something: `arr.reverse().map( e => console.log(e) );` using lambda and the reverse prototype, which is supported since ecmascript's first edition. https://jsfiddle.net/uoe33kk6/ – briosheje Dec 21 '16 at 16:19

3 Answers3

3

At first iteration, i is arr.length.

There's no element at index arr.length. The last element of a zero-based array is at index arr.length-1.

The usual way to iterate in reverse is

for (let i=arr.length; i-- > 0; ) {

(note that the condition decrements the counter and is executed before the content of the loop)

This can can also be simplified in JavaScript into

for (let i=arr.length; i--;) {
Denys Séguret
  • 372,613
  • 87
  • 782
  • 758
2

Why not use a while loop with a postfix decrement -- instead of a justified for loop?

var arr = [1, 2, 3, 4, 5, 6, 7, 8],
    i = arr.length;
  
while (i--) {
    console.log(arr[i]);
}
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
0

this happens because the length of the array from arr.length returns 8, and since the arrays in JavaScript are Zero-indexed (counting starts from 0), the last element in an array is at the index arr.length - 1

so to avoid the undefined, do this:

$(function(){

  var arr = [1,2,3,4,5,6,7,8]

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

})
Ally Jr
  • 1,055
  • 1
  • 14
  • 27