DEV Community

Sh Raj
Sh Raj

Posted on

For Loop through an array in backward direction in JavaScript

There are several methods to loop through the array in JavaScript in the reverse direction:

1. Using reverse for-loop

The standard approach is to loop backward using a for-loop starting from the end of the array towards the beginning of the array.

var arr = [1, 2, 3, 4, 5];

for (var i = arr.length - 1; i >= 0; i--) {
    console.log(arr[i]);
}
Enter fullscreen mode Exit fullscreen mode

2. Using Array.prototype.reverse() function

We know that forEach goes through the array in the forward direction. To loop through an array backward using the forEach method, we have to reverse the array. To avoid modifying the original array, first create a copy of the array, reverse the copy, and then use forEach on it. The array copy can be done using slicing or ES6 Spread operator.

var arr = [1, 2, 3, 4, 5];

arr.slice().reverse()
    .forEach(function(item) {
            console.log(item);
});

Enter fullscreen mode Exit fullscreen mode

Alternatively, you can use the Object.keys() method to get keys:

var arr = [1, 2, 3, 4, 5];

Object.keys(arr).reverse()
        .forEach(function(index) {
            console.log(arr[index]);
});
Enter fullscreen mode Exit fullscreen mode

3. Using Array.prototype.reduceRight() function

The reduceRight() method executes the callback function once for each element present in the array, from right-to-left. The following code example shows how to implement this.

var arr = [1, 2, 3, 4, 5];

arr.reduceRight((_, item) => console.log(item), null);
Enter fullscreen mode Exit fullscreen mode

That’s all about looping through an array backward in JavaScript.

Source :- https://www.techiedelight.com/loop-through-array-backwards-javascript/

Top comments (0)