Borislav Hadzhiev
Thu Nov 04 2021·2 min read
Photo by Irina Gorskaia
To use the forEach()
method on an array in reverse order:
slice()
method to get a copy of the array.reverse()
method to reverse the copied array.forEach()
method on the reversed array.const arr = ['a', 'b', 'c']; arr .slice() .reverse() .forEach(element => { console.log(element); // 👉️ c, b, a });
The first step is to use the Array.slice method to create a shallow copy of the array.
We do this because the Array.reverse method changes the contents of the original array in place.
Calling the slice()
method with no parameters returns a shallow copy of
original array, which we can reverse.
const arr = ['a', 'b', 'c']; const copy = arr.slice(); console.log(copy); // 👉️ ['a', 'b', 'c']
The reverse()
method reverses an array in place and returns the result.
const arr = ['a', 'b', 'c']; const reversed = arr.reverse(); console.log(reversed); // 👉️ ['c', 'b', 'a'] console.log(arr); // 👉️ ['c', 'b', 'a']
arr
variable was also reversed.This is the reason we created a shallow copy in advance - to avoid changing the original array.
The last step is to use the Array.forEach method on the reversed array.
An alternative approach is to use the spread syntax (...) to create a shallow copy of the array.
To use the forEach()
method on an array in reverse order:
reverse()
method to reverse the copied array.forEach()
method on the reversed array.const arr = ['a', 'b', 'c']; [...arr].reverse().forEach(element => { console.log(element); // 👉️ c, b, a });
The spread syntax (...) unpacks the values from the original array into a new array, creating a shallow copy.
We then reverse the copy to avoid mutating the original array and call the
forEach()
method on the reversed array.
reverse()
method, otherwise you'd end up changing the original array.