javascript loop through array backwards

Javascript Loop Through Array Backwards

Looping through an array is a common operation when working with arrays in Javascript. Sometimes, we may need to loop through the array backwards instead of forwards. There are different ways to loop through an array backwards in Javascript, we can use a for loop, while loop, or the forEach() method provided by arrays in ES6.

Using a for loop

We can loop through the array backwards using a for loop by starting the loop with the last index of the array and decrementing it until we reach the first index.


let arr = ["apple", "banana", "orange", "grape"];
for(let i = arr.length - 1; i >= 0; i--) {
  console.log(arr[i]);
}

In this example, we are looping through the array 'arr' backwards using a for loop. We start the loop with the last index of the array, which is 'arr.length - 1', and decrement 'i' until we reach the first index, which is 0. Inside the loop, we access each element of the array using the index 'i' and log it to the console.

Using a while loop

We can also use a while loop to iterate through the array backwards. We start with the last index of the array and decrement it until we reach the first index.


let arr = ["apple", "banana", "orange", "grape"];
let i = arr.length - 1;
while(i >= 0) {
  console.log(arr[i]);
  i--;
}

In this example, we are using a while loop to iterate through the array 'arr' backwards. We start with the last index of the array, which is 'arr.length - 1', and decrement 'i' until we reach the first index, which is 0. Inside the loop, we access each element of the array using the index 'i' and log it to the console.

Using forEach() method

In ES6, arrays come with a built-in forEach() method that allows us to loop through each element of the array. However, the forEach() method only iterates through the array in the forward direction. To loop through the array backwards using forEach() method, we can first reverse the array and then use forEach() method to iterate through it.


let arr = ["apple", "banana", "orange", "grape"];
arr.reverse().forEach(function(item) {
  console.log(item);
});

In this example, we are reversing the array 'arr' using reverse() method and then using forEach() method to iterate through it. Inside the loop, we access each element of the array using the argument 'item' and log it to the console.

These are some of the ways to loop through an array backwards in Javascript. Depending on the situation, we can choose the appropriate method that suits our needs.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe