Sub topic 8
toReversed: the related copying method
This chapter assumes you already know how toSorted, toSpliced, and with work, and that you are comfortable with Array.prototype.reverse, arrow functions, and the difference between primitive values and object references.
ES2023 added four copying methods to Array.prototype, not three. The fourth is toReversed. It is the copying counterpart of reverse, in the same way toSorted is the counterpart of sort. It takes no arguments, so it is the simplest of the four. It still has a few behaviors worth knowing, especially when you combine it with sorting.
What reverse does, and why it surprises people
reverse reverses an array in place and returns a reference to that same array. The return value makes it look like it produced a new array. It did not.
const steps = ["plan", "build", "test", "ship"];
const backwards = steps.reverse();
console.log(backwards); // ["ship", "test", "build", "plan"]
console.log(steps); // ["ship", "test", "build", "plan"] (changed)
console.log(backwards === steps); // trueThe common error is to treat backwards as an independent copy. Any later code that reads steps sees the reversed order, and any change made through backwards shows up in steps, because there is only one array.
The working model of toReversed
toReversed() creates a new array of the same length, fills it from the last index of the original down to the first, and returns it. The original array is untouched.
const steps = ["plan", "build", "test", "ship"];
const backwards = steps.toReversed();
console.log(backwards); // ["ship", "test", "build", "plan"]
console.log(steps); // ["plan", "build", "test", "ship"] (unchanged)
console.log(backwards === steps); // false
const empty = [];
console.log(empty.toReversed() === empty); // false: always a new arrayEven for an empty array or a one-element array, where reversing changes nothing, you get a new array. That guarantee matters in code that compares references to detect change. It also means you pay for an allocation every time, which costs little at normal sizes.
The four mutating and copying pairs
| Mutating method | Copying method | Arguments | What the copying method returns |
|---|---|---|---|
| `sort(compare)` | `toSorted(compare)` | optional comparator | new sorted array |
| `splice(start, deleteCount, ...items)` | `toSpliced(start, deleteCount, ...items)` | same as `splice` | new array after the edit, not the deleted items |
| `arr[i] = value` | `with(i, value)` | index, value | new array with one slot replaced |
| `reverse()` | `toReversed()` | none | new reversed array |
toReversed is the only one of the four whose return value has the same shape as the mutating version's. Both reverse and toReversed return the reversed array. Only the identity differs. That is why swapping one for the other compiles and runs without complaint, and why the bug from using reverse by mistake is easy to miss in review.
Shallow copy: the elements are shared
Like the other copying methods, toReversed copies references, not objects. The new array is new. The objects inside it are the same objects.
const tasks = [{ title: "Draft" }, { title: "Edit" }];
const latestFirst = tasks.toReversed();
console.log(latestFirst[0] === tasks[1]); // true
latestFirst[0].title = "Publish";
console.log(tasks[1].title); // "Publish"If you need to change an element in the reversed result without affecting the original, replace that element with a new object, for example with with and object spread, as covered in the chapter on immutable state.
Gotcha: reversing a sort is not the same as sorting in reverse
A common pattern is "sort ascending, then reverse to get descending." With copying methods it looks like this:
const descending = values.toSorted((a, b) => a - b).toReversed();For plain numbers this gives the same result as a descending comparator. For objects with equal sort keys it does not, because sort and toSorted are stable. A stable sort keeps elements that compare equal in their original relative order. Reversing afterward flips the order of those tied elements too.
const players = [
{ name: "Ana", score: 10 },
{ name: "Bo", score: 20 },
{ name: "Cy", score: 10 }
];
const viaComparator = players.toSorted((a, b) => b.score - a.score);
console.log(viaComparator.map((p) => p.name)); // ["Bo", "Ana", "Cy"]
const viaReverse = players
.toSorted((a, b) => a.score - b.score)
.toReversed();
console.log(viaReverse.map((p) => p.name)); // ["Bo", "Cy", "Ana"]Ana came before Cy in the input. The descending comparator keeps that order. The sort-then-reverse version puts Cy first. If ties should keep their input order, such as "most points first, then earliest signup," write a descending comparator instead of reversing.
Sparse arrays: holes become undefined
reverse keeps holes as holes. toReversed reads every index from 0 to length - 1, reads missing indices as undefined, and writes a real value into every slot of the result. The result is always dense.
const sparse = [1, , 3, , 5];
const copy = sparse.toReversed();
console.log(copy); // [5, undefined, 3, undefined, 1]
console.log(1 in copy); // true: the slot exists and holds undefined
const inPlace = [1, , 3, , 5];
inPlace.reverse();
console.log(1 in inPlace); // false: the hole is still a holeThis rarely matters in application code. It can matter if downstream code uses forEach or map, which skip holes but not undefined values. After toReversed, callbacks run for every index.
Array-like receivers and typed arrays
Array.prototype.toReversed is generic. It works on any object with a length property and indexed elements, and it always returns a plain Array. It ignores Symbol.species, so subclasses of Array also get a plain Array back.
const arrayLike = { length: 3, 0: "x", 1: "y", 2: "z" };
console.log(Array.prototype.toReversed.call(arrayLike)); // ["z", "y", "x"]
console.log(Array.prototype.toReversed.call("abc")); // ["c", "b", "a"]
class Stack extends Array {}
const stack = Stack.from([1, 2, 3]);
console.log(stack.toReversed() instanceof Stack); // false
console.log(Array.isArray(stack.toReversed())); // trueTyped arrays have their own toReversed on TypedArray.prototype. Unlike the Array version, it returns a new typed array of the same kind. Reversing does not change length, so typed arrays can support it, unlike toSpliced.
const samples = new Int16Array([10, -20, 30]);
const reversed = samples.toReversed();
console.log(reversed); // Int16Array [30, -20, 10]
console.log(reversed instanceof Int16Array); // true
console.log(samples); // Int16Array [10, -20, 30]Fallbacks for older runtimes
toReversed shipped together with the other ES2023 copying methods, so if toSorted is available, toReversed will be too. The fallback is a copy followed by an in-place reverse on that copy. Mutating a copy you just made is safe, because nothing else holds a reference to it yet.
function reversedCopy(arr) {
if (typeof Array.prototype.toReversed === "function") {
return arr.toReversed();
}
return [...arr].reverse();
}
console.log(reversedCopy([1, 2, 3])); // [3, 2, 1]The fallback differs from the native method in one small way. Spreading a sparse array also turns holes into undefined, so the results match. arr.slice().reverse() keeps holes, so it can differ from toReversed on sparse input. Prefer the spread version if you want identical behavior.
Common errors
| Mistake | What goes wrong | Fix |
|---|---|---|
| `const r = arr.reverse()` used as a copy | The original is reversed too; `r === arr` | Use `arr.toReversed()` |
| `arr.toReversed()` with the result discarded | Nothing changes; the call has no effect | Assign the result: `arr = arr.toReversed()` or use it directly |
| Sort ascending then reverse for a descending sort with ties | Tied elements come out in reverse input order | Use a descending comparator |
| Editing an object in the reversed copy | The original array's object changes as well | Replace the element with a new object |
| Expecting a subclass instance back | The result is a plain `Array` | Wrap it, for example `Stack.from(result)` |
Exercise
A component renders messages.reverse().map(renderMessage) to show the newest message first. Each re-render flips the order between oldest-first and newest-first. Explain why, and give a fixed version.
Show answer
reverse mutates messages in place, so each render reverses the array it reversed on the previous render, and the displayed order alternates. It also changes state the component does not own. The fix is messages.toReversed().map(renderMessage), which builds a new reversed array on every render and leaves messages unchanged.
Exercise
Given const items = [{ id: 1, rank: 2 }, { id: 2, rank: 1 }, { id: 3, rank: 2 }], what ids, in order, do items.toSorted((a, b) => a.rank - b.rank).toReversed() and items.toSorted((a, b) => b.rank - a.rank) produce?
Show answer
The ascending sort gives ids [2, 1, 3]. Reversing that gives [3, 1, 2]. The descending comparator gives [1, 3, 2], because the stable sort keeps id 1 before id 3 as in the input. The two approaches differ only in the order of the tied elements.
Exercise
What do the two logged values show for const t = new Uint8Array([1, 2, 3]); const r = t.toReversed(); console.log(r instanceof Uint8Array, Array.prototype.toReversed.call(t) instanceof Uint8Array)?
Show answer
true, then false. TypedArray.prototype.toReversed returns a new Uint8Array. Calling the generic Array.prototype.toReversed on the typed array treats it as an array-like object and returns a plain Array.