The Array.toReversed()
method is a new JavaScript function introduced in ECMAScript 2023 (ES14). It returns a new array with the elements of the original array reversed, leaving the original array unchanged.
Syntax
let newArray = arr.toReversed();
Parameters
The toReversed()
method does not take any parameters.
Return Value
This method returns a new array containing the elements of the original array in reverse order.
Example 1: Reversing a Simple Array
let arr = [10, 20, 30, 40, 50]; let revArr = arr.toReversed(); console.log(revArr); // Output: [ 50, 40, 30, 20, 10 ] console.log(arr); // Output: [ 10, 20, 30, 40, 50 ]
Example 2: Reversing a String Array
let arr = ['HTML', 'CSS', 'JavaScript', 'jQuery']; let revArr = arr.toReversed(); console.log(revArr); // Output: [ 'jQuery', 'JavaScript', 'CSS', 'HTML' ] console.log(arr); // Output: [ 'HTML', 'CSS', 'JavaScript', 'jQuery' ]
Example 3: Using toReversed()
with Nested Arrays
let arr = [[1, 2], [3, 4], [5, 6]]; let revArr = arr.toReversed(); console.log(revArr); // Output: [[5, 6], [3, 4], [1, 2]] console.log(arr); // Output: [[1, 2], [3, 4], [5, 6]]
Example 4: Comparing toReversed()
with reverse()
Method
let arr1 = [10, 20, 30, 40, 50]; let revArr1 = arr1.reverse(); console.log(revArr1); // Output: [ 50, 40, 30, 20, 10 ] console.log(arr1); // Output: [ 50, 40, 30, 20, 10 ] (mutated) let arr2 = [10, 20, 30, 40, 50]; let revArr2 = arr2.toReversed(); console.log(revArr2); // Output: [ 50, 40, 30, 20, 10 ] console.log(arr2); // Output: [ 10, 20, 30, 40, 50 ]
The reverse()
method modifies the original array, whereas toReversed()
returns a new array and preserves the original.
Supported Browsers
Browser | Support |
---|---|
Chrome | 110+ |
Firefox | 109+ |
Safari | 16.4+ |
Edge | 110+ |
Opera | 96+ |
Internet Explorer | Not Supported |