Array. prototype. toReversed()
Returns a new array with the elements in reverse order, without changing the original.
- Returns
- A new array with the elements in reverse order.
- Changes the original
- No
Example
#const levels = [1, 2, 3, 4]
const reversed = levels.toReversed()
console.log(reversed)
console.log(levels)Definition and usage
#The toReversed() method makes a copy of the array with its elements arranged from last to first. Unlike reverse(), it doesn’t touch the original, so you can safely reverse data that another part of the program relies on.
It belongs to the family of copying methods added in the ES2023 standard, together with toSorted(), toSpliced(), and with(). Each one has a mutating counterpart, but instead of changing the existing array, it returns a new one.
The copy is shallow: the objects inside aren’t cloned, so both arrays point to the same objects. Holes in sparse arrays turn into undefined in the copy.
Syntax
#array.toReversed()More examples
#const history = ['Lesson 1', 'Lesson 2', 'Lesson 3']
const newestFirst = history.toReversed()
console.log(newestFirst[0])
console.log(history[0])
history.reverse()
console.log(history[0])const students = [{ name: 'Emma' }, { name: 'Jack' }]
const reversed = students.toReversed()
reversed[0].name = 'Jacob'
console.log(students[1].name)
console.log(reversed === students)The arrays are different, but Jack’s object is the same one in both. So a change to its field through the copy shows up in the original too.
Browser support
#Widely available · since 2023
Works in all modern browsers, phones included. You can use it without worry.
- Chrome
- Edge
- Firefox
- Safari
Good practices
#- In React component state, use
toReversed()instead ofreverse(). Mutating the original array in state is a common cause of a view that won’t refresh. - In older code,
[...array].reverse()andarray.slice().reverse()give the same effect.
Related entries
#- Array.prototype.reverse()Reverses the order of the array’s elements in place.
- Array.prototype.toSorted()Returns a sorted copy of the array, leaving the original unchanged.
- Array.prototype.toSpliced()Removes, inserts, or replaces elements in a copy of the array. The original is left unchanged.
- Array.prototype.with()Returns a copy of the array in which the element at the given index has a new value.
Spotted a mistake or missing an example? Write to us.