JavaScript lovers, rejoice! The latest version of ES, ES14, has just introduced a brand new method that will flip your arrays upside down. Meet the "toReversed()" method!
Syntax:
array.toReversed()
Parameters: This method does not accept any parameters.
Return value: The toReversed()
method returns a new array with the elements in reverse order.
Notes:
- This method does not change the original array.
- It does not modify the original array in any way, it simply creates a new array with the elements in reverse order.
Example:
const arr = [1, 2, 3, 4, 5];
const reversedArr = arr.toReversed();
console.log(arr); // [1, 2, 3, 4, 5]
console.log(reversedArr); // [5, 4, 3, 2, 1]
The difference between reverse()
and toReversed()
:
const originalArray = [1, 2, 3, 4, 5];
// using `reverse()`
const reversedArray = originalArray.reverse();
console.log(reversedArray); // [5, 4, 3, 2, 1]
console.log(originalArray); // [5, 4, 3, 2, 1] - original array is modified!
// using `toReversed()`
const toReversedArray = originalArray.toReversed();
console.log(toReversedArray); // [1, 2, 3, 4, 5] - reversed copy of the original array
console.log(originalArray); // [1, 2, 3, 4, 5] - original array is unchanged!
In conclusion, the toReversed()
method is a useful method for creating a new array with the elements in reverse order. It is easy to use and does not modify the original array in any way, making it a safe and efficient way to manipulate arrays in JavaScript.
For more information, check out the following resources:
Top comments (0)