Array.prototype.toReversed(): reverse a copy (ES2023)
What you’ll learn
Section titled “What you’ll learn”- Why
reverse()causes bugs in code that shares arrays, and howtoReversed()avoids them. - What
toReversed()returns for holes, array-likes, subclasses and typed arrays. - How to reverse strings correctly, and when not to copy at all.
- Where
toReversed()fits among the other ES2023 copying methods.
Summary
Section titled “Summary”TL;DR: array.toReversed() returns a new array with the elements in reverse order and leaves array untouched. It is the non-mutating counterpart of reverse().
It was added in ECMAScript 2023 by the “Change Array by Copy” proposal, together with toSorted(), toSpliced() and with(). It is supported in all current browsers and Node.js 20+ (see Compatibility).
The problem it solves
Section titled “The problem it solves”reverse() reverses the array in place and returns the same array. Code like const newestFirst = events.reverse() reads as if it creates a new value, but it silently reorders events for every other piece of code holding that reference: a UI framework’s state, a cache, the caller’s argument. The usual workaround, [...events].reverse() or events.slice().reverse(), works but is easy to forget.
Running the samples: save a sample as a .mjs file and run it with Node.js 22 (node sample.mjs). All outputs shown were produced with Node.js 22.23. The examples use an invented order-management app, OrdersPortal.
const events = ['created', 'paid', 'packed', 'shipped'];
// Before: reverse() mutates in place and returns the same array.const newestFirst = events.reverse();console.log(newestFirst === events, events);
// After: toReversed() returns a new array and leaves the original alone.const log = ['created', 'paid', 'packed', 'shipped'];const timeline = log.toReversed();console.log(timeline === log, log, timeline);Output:
true [ 'shipped', 'packed', 'paid', 'created' ]false [ 'created', 'paid', 'packed', 'shipped' ] [ 'shipped', 'packed', 'paid', 'created' ]How it works
Section titled “How it works”toReversed() takes no arguments. Per the specification, it reads the receiver’s length, creates a new plain Array of that length, and copies element length - k - 1 into slot k. Consequences:
- Holes become
undefined.[1, , 3].toReversed()is[3, undefined, 1], a dense array.reverse()keeps holes. - It is generic. It works on any array-like through
Array.prototype.toReversed.call(obj). - The result is always a plain
Array, never a subclass instance, unlikereverse(), which returns the receiver itself. - It is shallow. The new array holds the same object references.
- Typed arrays have their own
TypedArray.prototype.toReversed(), which returns a typed array of the same type.
console.log([1, , 3].toReversed()); // hole becomes undefinedconsole.log([].toReversed());
// Generic: works on array-likes, always returns a plain Array.const arrayLike = { length: 3, 0: 'a', 1: 'b', 2: 'c' };console.log(Array.prototype.toReversed.call(arrayLike));
class OrderList extends Array {}const list = OrderList.from(['o-1', 'o-2']);console.log(list.toReversed() instanceof OrderList, list.reverse() instanceof OrderList);
// Typed arrays have their own toReversed().console.log(new Uint8Array([1, 2, 3]).toReversed());
// Shallow: the copy holds the same objects.const orders = [{ id: 'o-1' }, { id: 'o-2' }];const reversed = orders.toReversed();reversed[0].id = 'changed';console.log(orders[1].id);
// Strings: there is no String.prototype.toReversed. Spread into code points first.console.log([...'stressed'].toReversed().join(''));console.log([...'ok👍🏽'].toReversed().join('') === '🏽👍ko');Output:
[ 3, undefined, 1 ][][ 'c', 'b', 'a' ]false trueUint8Array(3) [ 3, 2, 1 ]changeddessertstrueThe last line shows a limit of code-point reversal: the skin-tone modifier is separated from its emoji. To reverse user-visible characters, split into grapheme clusters with Intl.Segmenter:
const text = 'ok👍🏽';const graphemes = Array.from( new Intl.Segmenter('en', { granularity: 'grapheme' }).segment(text), (s) => s.segment,);console.log(graphemes.toReversed().join('') === '👍🏽ko'); // trueRealistic example
Section titled “Realistic example”OrdersPortal keeps an append-only audit log per order. The order page shows the most recent activity first; the CSV export lists events oldest first. Neither view may reorder the log.
const auditLog = [];const record = (orderId, action) => auditLog.push({ at: auditLog.length + 1, orderId, action });
record('o-204', 'created');record('o-204', 'paid');record('o-204', 'address changed');record('o-204', 'shipped');
const recentActivity = (log, limit) => log.toReversed().slice(0, limit);const csv = (log) => log.map((e) => `${e.at},${e.orderId},${e.action}`).join('\n');
console.log(recentActivity(auditLog, 2));console.log(csv(auditLog));Output:
[ { at: 4, orderId: 'o-204', action: 'shipped' }, { at: 3, orderId: 'o-204', action: 'address changed' }]1,o-204,created2,o-204,paid3,o-204,address changed4,o-204,shippedHad recentActivity used log.reverse(), the CSV export would come out newest first after the page rendered once, and every later call would flip the order again.
toReversed() copies the whole log to keep two entries. For a long log, take the tail first or read backward:
const auditLog = Array.from({ length: 100_000 }, (_, i) => ({ at: i + 1 }));
function lastN(arr, n) { const out = []; for (let i = arr.length - 1; i >= 0 && out.length < n; i--) out.push(arr[i]); return out;}console.log(lastN(auditLog, 3).map((e) => e.at));console.log(auditLog.slice(-3).toReversed().map((e) => e.at));Output:
[ 100000, 99999, 99998 ][ 100000, 99999, 99998 ]Common mistakes
Section titled “Common mistakes”- Assuming
reverse()returns a copy. It returns the same, now reversed, array. UsetoReversed()whenever the array is shared. - Expecting a deep copy. Mutating an element of the reversed array mutates the original element.
- Copying just to find something. To find the last match, use
findLast(); to read the last element, useat(-1). Neither allocates. - Reversing a large array to show a few items.
slice(-n).toReversed()copies onlynelements. - Calling it on a string. Strings have no
toReversed; spread or segment first, as shown above. - Relying on holes. Sparse arrays come back dense, with
undefinedwhere the holes were.
When to use it and when not to
Section titled “When to use it and when not to”| Need | Use |
|---|---|
| Reversed view of a shared or state array | toReversed() |
| Reverse a local array nobody else references | reverse() (no allocation) |
| Last element or last match | at(-1), findLast(), findLastIndex() |
| Iterate backward once | a for loop from length - 1 down |
| Sorted copy in descending order | toSorted((a, b) => b - a), not toSorted().toReversed() |
| Replace one element in a copy | with() |
Compatibility
Section titled “Compatibility”According to MDN’s browser compatibility data, Array.prototype.toReversed and TypedArray.prototype.toReversed are supported in Chrome 110, Edge 110, Firefox 115, Safari 16 (including iOS), Node.js 20.0.0, Deno 1.31 and Bun 1.0. Internet Explorer never supported them.
TypeScript: the typings are in lib.es2023.array.d.ts. With an older lib or target, TypeScript 6.0 reports Property 'toReversed' does not exist on type ... and suggests changing lib to es2023 or later. TypeScript does not polyfill it; for Node.js 18 or older browsers use core-js or keep [...arr].reverse().
Interview questions
Section titled “Interview questions”1. What is the difference between reverse() and toReversed()?
reverse() mutates the array in place and returns the same reference. toReversed() returns a new plain array and leaves the original unchanged. toReversed() also turns holes into undefined.
2. Why is const b = a.reverse() a common bug in React or Redux code?
State updates are detected by reference. reverse() mutates the existing state array and returns the same reference, so the change can be missed and every other reader of the old state sees the new order. toReversed() produces a new reference and leaves the old state intact.
3. Senior scenario: a feed renders the newest 20 items from an array of 200,000 events on every update, using events.toReversed().slice(0, 20). Profiling shows high allocation. What do you change?
The code copies 200,000 references to keep 20. Use events.slice(-20).toReversed(), or a backward loop, so the cost is proportional to the page size. If the feed always needs newest first, consider storing events in that order or memoizing the view so it is computed only when the events change.
Key takeaways
Section titled “Key takeaways”toReversed()(ES2023) returns a reversed copy;reverse()mutates.- The copy is shallow, dense and always a plain
Array. - Typed arrays have their own
toReversed(). - Don’t copy a whole array to read a few items from its end.
Related pages
Section titled “Related pages”- Array.prototype.toSorted: the non-mutating
sort(). - Array.prototype.with: replace one element in a copy.
- Array.prototype.findLast: search from the end without copying.
- Array.prototype.at: read from the end with negative indexes.
- Array.from: build arrays from iterables and array-likes.
- Arrays (basics)
Official references
Section titled “Official references”- ECMAScript Language Specification,
Array.prototype.toReversed ( )(current draft; first published in ECMAScript 2023) - ECMAScript 2023 Language Specification (ECMA-262, 14th edition)
- TC39 proposal: Change Array by Copy
- MDN: Array.prototype.toReversed()
- MDN: Intl.Segmenter