Array.toReversed()
The Array.toReversed()
method in JavaScript creates a new array with the elements of the original array in reverse order. Unlike the Array.reverse()
method, this does not modify the original array but instead returns a new one.
Syntax
toReversed()
Parameters
The toReversed()
method does not accept any parameters.
Return Value
The toReversed()
method returns a new array with the elements of the calling array in reverse order. The original array remains unmodified.
Examples
1. Reversing an Array
This example demonstrates how to reverse the elements of an array without modifying the original array.
const numbers = [1, 2, 3, 4, 5];
const reversedNumbers = numbers.toReversed();
console.log(reversedNumbers); // [5, 4, 3, 2, 1]
console.log(numbers); // [1, 2, 3, 4, 5] (original array is unchanged)
Output
[5, 4, 3, 2, 1]
[1, 2, 3, 4, 5]
toReversed()
creates a new array with elements in reverse order.- The original
numbers
array remains unchanged.
2. Using toReversed()
on Strings
The toReversed()
method can be used to reverse arrays of strings.
const words = ["apple", "banana", "cherry"];
const reversedWords = words.toReversed();
console.log(reversedWords); // ["cherry", "banana", "apple"]
console.log(words); // ["apple", "banana", "cherry"] (original array is unchanged)
Output
["cherry", "banana", "apple"]
["apple", "banana", "cherry"]
toReversed()
reverses the order of the strings in the array.- The original
words
array remains unchanged.
3. Chaining with Other Methods
The toReversed()
method can be chained with other array methods, such as map()
and filter()
.
const numbers = [1, 2, 3, 4, 5];
const modifiedNumbers = numbers.toReversed().map(num => num * 2);
console.log(modifiedNumbers); // [10, 8, 6, 4, 2]
Output
[10, 8, 6, 4, 2]
This demonstrates how toReversed()
integrates seamlessly with other array methods.
4. Comparing toReversed()
with reverse()
The toReversed()
method creates a new reversed array, while reverse()
modifies the original array.
const numbers = [1, 2, 3, 4, 5];
// Using reverse()
const reversedNumbers1 = numbers.reverse();
console.log(reversedNumbers1); // [5, 4, 3, 2, 1]
console.log(numbers); // [5, 4, 3, 2, 1] (original array is modified)
// Using toReversed()
const numbers2 = [1, 2, 3, 4, 5];
const reversedNumbers2 = numbers2.toReversed();
console.log(reversedNumbers2); // [5, 4, 3, 2, 1]
console.log(numbers2); // [1, 2, 3, 4, 5] (original array is unchanged)
Output
[5, 4, 3, 2, 1]
[5, 4, 3, 2, 1]
[5, 4, 3, 2, 1]
[1, 2, 3, 4, 5]
This highlights the difference between toReversed()
and reverse()
.