JavaScript Array.prototype.reverse() vs Array.prototype.toReversed()
The reverse()
array method reverses its elements in place (no copy is made) and returns a reference to the same array. Hence, it mutates the array.
> const arr = [1, 2, 3, 4, 5]
undefined
> arr.reverse() // Returns a reference to the original array, now reversed
[ 5, 4, 3, 2, 1 ]
> console.log(arr) // Original array mutated
[ 5, 4, 3, 2, 1 ]
The TC39 Change Array by copy proposal introduced a new method Array.prototype.toReversed()
that does the same thing as reverse()
but returns a new copy with the changes instead of mutating the array in place.
> const arr = [1, 2, 3, 4, 5];
undefined
> arr.toReversed() // Returns a new copy of the array that is reversed
[5, 4, 3, 2, 1]
> arr
[1, 2, 3, 4, 5] // Original array is not mutated