Reverse an Array without Modifying the Original in JS

avatar

Borislav Hadzhiev

Last updated: Nov 4, 2021

banner

Photo from Unsplash

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 #

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.