How toReversed() method is different from reverse() method in JavaScript
Last Updated :
06 Dec, 2023
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]
Share your thoughts in the comments
Please Login to comment...