DEV Community

Cover image for Comparing JavaScript Array Methods: reverse() vs toReversed()
Ahmad Adibzad
Ahmad Adibzad

Posted on

2

Comparing JavaScript Array Methods: reverse() vs toReversed()

The reverse() function in JavaScript is commonly used to reverse an array. However, there is a new function called the toReversed(), which may be more suitable depending on the situation. Your code might have unexpected results if you use reverse() without knowing its effects.

The main difference is that the reverse() function changes the original array. For example, we are going to reverse the following array using the reverse function:

reverse():

const arr = [1,2,3];
arr.reverse();
console.log(arr); // [3,2,1]
Enter fullscreen mode Exit fullscreen mode

As you can see, the original array has mutated because the reverse() returns a reference to the original array. Now let's use the toReversed(). This function returns a copy of the original array and doesn't change it:

toReversed():

const arr = [1,2,3];
arr.toReversed();
console.log(arr); // [1,2,3]
Enter fullscreen mode Exit fullscreen mode

The next difference we must know is that empty slots remain empty in the reverse() function, while in toReversed() empty slots become undefined.

reverse():

const arr = [1,2,3];
delete arr[0];
arr.reverse();
console.log(arr); // [3, 2, empty]
Enter fullscreen mode Exit fullscreen mode

toReversed():

const arr = [1,2,3];
delete arr[0];
const arr2 = arr.toReversed();
console.log(arr2) // [3, 2, undefined]
Enter fullscreen mode Exit fullscreen mode

Image of Docusign

🛠️ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs