Reverse an Array without Modifying the Original in JS

avatar

Borislav Hadzhiev

Thu Nov 04 20212 min read

Reverse an Array without Modifying the Original #

To reverse an array without modifying the original, call the slice() method on the array to create a shallow copy and call the reverse() method on the copy, e.g. arr.slice().reverse(). The reverse method will not modify the original array when used on the copy.

index.js
const arr = ['a', 'b', 'c']; const reversed1 = arr.slice().reverse(); console.log(reversed1); // ๐Ÿ‘‰๏ธ ['c', 'b', 'a'] console.log(arr); // ๐Ÿ‘‰ ๏ธ['a', 'b', 'c']

The first step is to create a shallow copy of the array by using the Array.slice method.

index.js
const arr = ['a', 'b', 'c']; const copy = arr.slice(); console.log(copy); // ๐Ÿ‘‰๏ธ ['a', 'b', 'c']
When the slice method is called without supplying any parameters, it returns a shallow copy of the original array.

The last step is to use the Array.reverse method on the copied array.

The reverse() method reverses the array in place and returns the result.

The original array is not mutated, because we called the reverse() method on a copy of the array.

An alternative approach is to use the spread syntax (...).

To reverse an array without modifying the original:

  1. Use the spread syntax (...) to create a copy of the array.
  2. Call the reverse() method on the copy.
  3. The final array will contain the elements in reversed order.
index.js
const arr = ['a', 'b', 'c']; const reversed2 = [...arr].reverse(); console.log(reversed2); // ๐Ÿ‘‰๏ธ ['c', 'b', 'a'] console.log(arr); // ๐Ÿ‘‰ ๏ธ['a', 'b', 'c']

We used the spread syntax (...) to unpack the values of the array into a new array, creating a shallow copy.

This enables us to use the reverse() method without modifying the original array.

Which approach you pick is a matter of personal preference. I prefer the spread syntax (...) approach as I find it easier to read, even though using the slice method might be a little bit faster when dealing with large arrays.

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