DEV Community

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

Posted on

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

Top comments (0)