EN
JavaScript - iterate array backwards
0 points
In this article, we would like to show you how to iterate an array backwards in JavaScript.
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
).
xxxxxxxxxx
1
var array = [1, 2, 3];
2
3
for (var i = array.length - 1; i >= 0; --i) {
4
console.log(array[i]);
5
}
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()
.
xxxxxxxxxx
1
const array = [1, 2, 3];
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.