Skip to content Skip to sidebar Skip to footer

Reversed For Loop - First Iteration Undefined

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

Solution 1:

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--;) {

Solution 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]);
}

Solution 3:

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]);
  }

})

Post a Comment for "Reversed For Loop - First Iteration Undefined"