Get started with 33% off your first certification using code: 33OFFNEW

How to reverse an array in JavaScript

1 min read
Published on 2nd August 2023
How to reverse an array in JavaScript

JavaScript provides an array of methods to perform different operations on arrays. Among those methods, Array.reverse() stands out for its simplicity and effectiveness in reversing arrays. However, as a JavaScript developer, you might also want to know how to reverse an array without mutating the original array. This article will explore both of these topics.

Using Array.reverse()

The Array.reverse() method is the most straightforward way to reverse an array in JavaScript. This method mutates the original array by reversing the order of its elements in-place.

Here is an example:

let arr = [1, 2, 3, 4, 5];
arr.reverse();

console.log(arr); // Outputs: [5, 4, 3, 2, 1]

As you can see, the Array.reverse() method is extremely simple to use. However, it's important to remember that this method changes the original array.

Introducing the Array.toReversed() Method

In many cases, you may want to reverse an array without mutating the original array. JavaScript introduced Array.toReversed() to do just that.

Here is how you can use it:

let arr = [1, 2, 3, 4, 5];
let reversedArr = arr.toReversed();

console.log(arr); // Outputs: [1, 2, 3, 4, 5]
console.log(reversedArr); // Outputs: [5, 4, 3, 2, 1]

You should always try and avoid mutating existing data objects wherever possible.