To use forEach() on an array in reverse order in JavaScript, you will need to create a copy of the array, reverse the new array and then use forEach() on that new array.
Let’s discuss this method in detail below.
Use forEach() On An Array In Reverse Order In JavaScript
This can be done with the following code:
var arr = ['a', 'b', 'c'];
var reversedArr = arr.slice().reverse();
reversedArr.forEach(function(element) {
console.log(element);
});
Output
“c”
“b”
“a”
In the above code, we have created a copy of the array using arr.slice(). We have then reversed that new array using Array.reverse() and finally used forEach() to loop through each element in reverse order.
arr.slice() method is used to create a shallow copy of an array.
Array.reverse() is used to reverse the order of the elements in an array.
forEach() method executes a provided function once for each element in an array in ascending order.
You can create a copy of the array using the spread operator (…) like so:
var arr = ['a', 'b', 'c'];
var reversedArr = [...arr].reverse();
reversedArr.forEach(function(element) {
console.log(element);
});
Output: “c” “b” “a”
In the above code, we have used the spread operator (…) to create a copy of the array and then reversed that new array using Array.reverse(). We have then used forEach() to loop through each element in reverse order.
The spread operator (…) allows an iterable to be expanded in places where 0+ arguments are expected.
Both these approaches are fine but do make sure you create a copy of the array before reversing it as Array.reverse() changes the order of elements in the original array as well, and we don’t want to change the original array.
Conclusion
In this article, you have learned how to use forEach() on an array in reverse order in JavaScript. You have also learned about the importance of creating a copy of the array before reversing it using Array.reverse(). Thanks for reading! 🙂