JavaScript Array toReversed()
Syntax & Examples
Array.toReversed() method
The toReversed() method of the Array class in JavaScript returns a new array with the elements in reversed order, without modifying the original array.
Syntax of Array.toReversed()
The syntax of Array.toReversed() method is:
toReversed()
This toReversed() method of Array returns a new array with the elements in reversed order, without modifying the original array.
Return Type
Array.toReversed() returns value of type Array
.
✐ Examples
1 Using toReversed() method to create a reversed array
In JavaScript, we can use the toReversed() method to create a new array with elements in reversed order.
For example,
- We define an array variable arr with elements [1, 2, 3, 4, 5].
- We use the toReversed() method on arr to create a new array with reversed elements.
- The order of elements in the new array is reversed compared to arr.
- We log the new array to the console using console.log() method to see the reversed order.
JavaScript Program
const arr = [1, 2, 3, 4, 5];
const reversedArray = arr.toReversed();
console.log(reversedArray);
Output
[5, 4, 3, 2, 1]
2 Using toReversed() method with a string array
We can also use the toReversed() method with an array of strings to create a new array with reversed string elements.
For example,
- We define a string array variable strArr with elements ['apple', 'banana', 'cherry', 'date'].
- We use the toReversed() method on strArr to create a new array with reversed string elements.
- The order of strings in the new array is reversed compared to strArr.
- We log the new array to the console using console.log() method to see the reversed order of strings.
JavaScript Program
const strArr = ['apple', 'banana', 'cherry', 'date'];
const reversedStrArray = strArr.toReversed();
console.log(reversedStrArray);
Output
['date', 'cherry', 'banana', 'apple']
Summary
In this JavaScript tutorial, we learned about toReversed() method of Array: the syntax and few working examples with output and detailed explanation for each example.