The toReversed()
method of Array
instances is the copying counterpart of the reverse()
method. It returns a new array with the elements in reversed order.
The toReversed()
method of Array
instances is the copying counterpart of the reverse()
method. It returns a new array with the elements in reversed order.
toReversed()
None.
A new array containing the elements in reversed order.
The toReversed()
method transposes the elements of the calling array object in reverse order and returns a new array.
When used on sparse arrays, the toReversed()
method iterates empty slots as if they have the value undefined
.
The toReversed()
method is generic. It only expects the this
value to have a length
property and integer-keyed properties.
The following example creates an array items
, containing three elements, then creates a new array that's the reverse of items
. The items
array remains unchanged.
const items = [1, 2, 3]; console.log(items); // [1, 2, 3] const reversedItems = items.toReversed(); console.log(reversedItems); // [3, 2, 1] console.log(items); // [1, 2, 3]
The return value of toReversed()
is never sparse. Empty slots become undefined
in the returned array.
console.log([1, , 3].toReversed()); // [3, undefined, 1] console.log([1, , 3, 4].toReversed()); // [4, 3, undefined, 1]
The toReversed()
method reads the length
property of this
. It then visits each property having an integer key between length - 1
and 0
in descending order, adding the value of the current property to the end of the array to be returned.
const arrayLike = { length: 3, unrelated: "foo", 2: 4, }; console.log(Array.prototype.toReversed.call(arrayLike)); // [4, undefined, undefined] // The '0' and '1' indices are not present so they become undefined
Desktop | Mobile | Server | ||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
Chrome | Edge | Firefox | Opera | Safari | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | WebView Android | Deno | Node.js | ||
toReversed |
110 | 110 | 115 | 96 | 16 | 110 | 115 | 74 | 16 | 21.0 | 110 | 1.31 | 20.0.0 |
© 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/toReversed