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 Timescale

Timescale – the developer's data platform for modern apps, built on PostgreSQL

Timescale Cloud is PostgreSQL optimized for speed, scale, and performance. Over 3 million IoT, AI, crypto, and dev tool apps are powered by Timescale. Try it free today! No credit card required.

Try free

Top comments (0)

Heroku

Simplify your DevOps and maximize your time.

Since 2007, Heroku has been the go-to platform for developers as it monitors uptime, performance, and infrastructure concerns, allowing you to focus on writing code.

Learn More

👋 Kindness is contagious

Explore a sea of insights with this enlightening post, highly esteemed within the nurturing DEV Community. Coders of all stripes are invited to participate and contribute to our shared knowledge.

Expressing gratitude with a simple "thank you" can make a big impact. Leave your thanks in the comments!

On DEV, exchanging ideas smooths our way and strengthens our community bonds. Found this useful? A quick note of thanks to the author can mean a lot.

Okay