Use forEach() on an Array in Reverse Order in JavaScript

avatar

Borislav Hadzhiev

Thu Nov 04 20212 min read

Use forEach() on an Array in Reverse Order #

To use the forEach() method on an array in reverse order:

  1. Use the slice() method to get a copy of the array.
  2. Use the reverse() method to reverse the copied array.
  3. Call the forEach() method on the reversed array.
index.js
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.

index.js
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.

index.js
const arr = ['a', 'b', 'c']; const reversed = arr.reverse(); console.log(reversed); // ๐Ÿ‘‰๏ธ ['c', 'b', 'a'] console.log(arr); // ๐Ÿ‘‰๏ธ ['c', 'b', 'a']
Notice that the original array stored in the 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:

  1. Use the spread syntax (...) to get a copy of the array.
  2. Use the reverse() method to reverse the copied array.
  3. Call the forEach() method on the reversed array.
index.js
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.

Either approach works just fine, but make sure you create a copy of the array before using the reverse() method, otherwise you'd end up changing the original array.

Further Reading #

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee