EN
JavaScript - iterate array backwards
0
points
In this article, we would like to show you how to iterate an array backwards in JavaScript.
1. Using for loop
In this example, we use a simple for loop to iterate the array from the last element (with index = array.length - 1) to the first one by decrementing the iterator (--i).
// ONLINE-RUNNER:browser;
var array = [1, 2, 3];
for (var i = array.length - 1; i >= 0; --i) {
console.log(array[i]);
}
2. Using reverse() method with forEach()
In this example, we use slice() method to create a shallow copy of an array, then we use reverse() method to reverse the copy. Finally, we iterate the reversed copy of array using forEach().
// ONLINE-RUNNER:browser;
const array = [1, 2, 3];
array.slice().reverse().forEach((item) => console.log(item));
Warning:
This is not a good solution because the array is copied first, then the copy is reversed and it is iterated at the end.