JavaScriptArrays

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
On this page

Example

#
JavaScript
const levels = [1, 2, 3, 4]
const reversed = levels.toReversed()

console.log(reversed)
console.log(levels)
Console
[4, 3, 2, 1]
[1, 2, 3, 4]

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

#
Syntax
array.toReversed()

More examples

#
reverse() vs. toReversed()
JavaScript
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])
Console
Lesson 3
Lesson 1
Lesson 3
The copy is shallow
JavaScript
const students = [{ name: 'Emma' }, { name: 'Jack' }]
const reversed = students.toReversed()

reversed[0].name = 'Jacob'
console.log(students[1].name)
console.log(reversed === students)
Console
Jacob
false

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 of reverse(). Mutating the original array in state is a common cause of a view that won’t refresh.
  • In older code, [...array].reverse() and array.slice().reverse() give the same effect.

Related entries

#

Spotted a mistake or missing an example? Write to us.