The Wayback Machine - https://web.archive.org/web/20240118175229/https://www.geeksforgeeks.org/how-toreversed-method-is-different-from-reverse-method-in-javascript/
Open In App
Related Articles

How toReversed() method is different from reverse() method in JavaScript

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Report issue
Report

In JavaScript, reverse() and toReversed() methods do the same job as reversing but toReversed() does not change the original array. The reverse() method changes the original array. Below we have explained both methods.

Reverse() Method

The reverse() method is a built-in method for arrays in JavaScript that directly modifies the array in place and returns the same array reference.

Syntax:

arr.reverse()

Example: In this example, We have used reverse() method to reverse an array. Here, we can see that reverse() method changes the original array.

Javascript




let arr = [1, 2, 3, 4, 5, 6, 7]
let arr2 = arr.reverse();
 
console.log("arr : ", arr);
console.log("arr2 : ", arr2);


Output

arr :  [
  7, 6, 5, 4,
  3, 2, 1
]
arr2 :  [
  7, 6, 5, 4,
  3, 2, 1
]

toReversed() method

The toReversed() method of array instances is the copying of the reverse() method. It returns a new array with the elements in reversed order and original array remains unaffected.

Syntax:

let arr2 = arr.toReversed()

Example: In this example, We have used toReversed() method. Here we can see that toReversed() method does not change the original array.

Javascript




let arr = [1, 2, 3, 4, 5, 6, 7];
 
let arr2 = arr.toReversed();
 
console.log("arr : ", arr);
console.log("arr2 ; ", arr2);


Output:

arr : [1, 2, 3, 4, 5, 6, 7]
arr2 : [7, 6, 5, 4, 3, 2, 1]

Note: When used on Sparse arrays, the toReversed() method takes empty slots as if they have the value undefined.

Javascript




let arr = [1, 2, , 4, , 5, 6, 7];
let arr2 = arr.reverse();
console.log("arr2 : ", arr2);
 
let arr3 = [1, 2, , 4, , 5, 6, 7];
let arr4 = arr3.toReversed();
console.log("arr4 : ", arr4)


Output:

arr2 : [7, 6, 5, empty, 4, empty, 2, 1]
arr4 : [7, 6, 5, undefined, 4, undefined, 2, 1]

Learn to code easily with our course Coding for Everyone. This course is accessible and designed for everyone, even if you're new to coding. Start today and join millions on a journey to improve your skills!

Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out - check it out now!

Commit to GfG's Three-90 Challenge! Purchase a course, complete 90% in 90 days, and save 90% cost click here to explore.
Last Updated : 06 Dec, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads
Complete Tutorials