Sub topic 14
Array-like receivers and why the result is always a plain Array
This chapter assumes you already know how toSorted, toSpliced, with, and toReversed behave on ordinary arrays. It also assumes you know what Function.prototype.call does and that you have seen class ... extends Array. Two questions remain. First, what happens when one of these methods runs on something that is not an array? Second, why does every result come back as a plain Array, even when you call the method on a subclass?
What "generic" means for these methods
A generic array method does not require its this value to be a real array. It needs only an object it can read a length from, plus indexed properties 0, 1, 2, and so on. Any such object is called an array-like. arguments, DOM NodeLists, strings, and hand-built objects such as { length: 2, 0: "b", 1: "a" } are all array-likes.
All four ES2023 copying methods are generic. You reach them through Array.prototype and supply the receiver with call:
const arrayLike = { length: 3, 0: "c", 1: "a", 2: "b" };
console.log(Array.prototype.toSorted.call(arrayLike)); // ["a", "b", "c"]
console.log(Array.prototype.toReversed.call(arrayLike)); // ["b", "a", "c"]
console.log(Array.prototype.toSpliced.call(arrayLike, 1, 1)); // ["c", "b"]
console.log(Array.prototype.with.call(arrayLike, -1, "z")); // ["c", "a", "z"]
console.log(arrayLike); // { '0': 'c', '1': 'a', '2': 'b', length: 3 } (unchanged)The methods never write to the receiver. They read from it and write only into the new array. This is the main difference from the mutating methods, which also work on array-likes but change them in place:
const target = { length: 3, 0: "c", 1: "a", 2: "b" };
const returned = Array.prototype.sort.call(target);
console.log(returned === target); // true: sort returns the same object
console.log(Array.isArray(returned)); // false
console.log(target[0], target[1], target[2]); // a b c (mutated)The two methods also return different things. sort gives you back the receiver, so the result is still an array-like object. toSorted always gives you a real array.
The algorithm step by step
The specification describes all four methods with the same few steps. Once you know those steps you can predict every edge case in this chapter.
Here is what each step means in practice.
ToObject(this)turns primitives into wrapper objects, so a string works as a receiver.nullandundefinedthrow aTypeError.lengthis read once and converted withToLength. A missinglengthbecomes0,"3"becomes3, negative values become0, and fractions are truncated.- The result comes from
ArrayCreate, the internal operation behind a plain[]. It never consults the receiver's constructor. - Each index is read with an ordinary property get. The method never checks whether a property exists, so missing indices come back as
undefined. The sparse-array chapter covers the same behaviour.
toSorted performs one check before all of these steps. If you pass a comparator that is neither a function nor undefined, it throws a TypeError before it touches the receiver.
Watching the reads with a Proxy
A Proxy with a get trap shows exactly what the method touches:
const source = { length: 3, 0: 30, 1: 10, 2: 20 };
const logged = new Proxy(source, {
get(obj, prop, receiver) {
if (typeof prop === "string") console.log("get", prop);
return Reflect.get(obj, prop, receiver);
},
set() {
throw new Error("copying methods should never write to the receiver");
}
});
const result = Array.prototype.toSorted.call(logged, (a, b) => a - b);
// get length
// get 0
// get 1
// get 2
console.log(result); // [10, 20, 30]The method reads length once and each index once, and the set trap never fires. Getters on the receiver therefore run exactly once per index, in ascending order. This matters if your getters have side effects or are expensive.
Common receivers and their gotchas
| Receiver | Works? | Result of `Array.prototype.toReversed.call(x)` | Note |
|---|---|---|---|
| `"abc"` | Yes | `["c", "b", "a"]` | Indexes by UTF-16 code unit, so emoji and other surrogate pairs split apart |
| `arguments` | Yes | Reversed arguments | Rest parameters make this unnecessary in modern code |
| `NodeList` (browser) | Yes | Plain array of nodes | The live DOM is untouched |
| `{ length: "2", 0: "a", 1: "b" }` | Yes | `["b", "a"]` | `length` is coerced to a number |
| `{ 0: "a", 1: "b" }` | Yes, but empty | `[]` | No `length` means length `0` |
| `new Set([1, 2])` | Yes, but empty | `[]` | Sets have `size`, not `length` |
| `null` / `undefined` | No | `TypeError` | `ToObject` fails |
| `{ length: 2 ** 32 }` | No | `RangeError` | Too long for a real array |
The Set row is the one that catches people. Generic methods read length and indices. They do not use the iterator protocol. If your source is iterable but has no indices, convert it first:
const tags = new Set(["b", "c", "a"]);
console.log(Array.prototype.toSorted.call(tags)); // [] (silent failure)
console.log(Array.from(tags).toSorted()); // ["a", "b", "c"]
console.log([...tags].toSorted()); // ["a", "b", "c"]Strings make a good test case because they are primitives:
console.log(Array.prototype.toSorted.call("banana")); // ["a", "a", "a", "b", "n", "n"]
console.log(Array.prototype.with.call("cat", 0, "b").join("")); // "bat"Because no write ever reaches the receiver, frozen objects and frozen arrays are fine receivers. With sort they are not:
const frozen = Object.freeze([3, 1, 2]);
console.log(frozen.toSorted()); // [1, 2, 3]
try {
frozen.sort();
} catch (err) {
console.log(err instanceof TypeError); // true
}Why the result is never a subclass
Older methods such as map, filter, slice, concat, and flat build their result with an internal step called ArraySpeciesCreate. That step reads this.constructor[Symbol.species] and constructs the result with whatever it finds. As a result, map on a subclass instance normally returns an instance of the same subclass.
The ES2023 copying methods skip that lookup and call ArrayCreate directly:
class TaggedList extends Array {}
const list = TaggedList.from([3, 1, 2]);
console.log(list instanceof TaggedList); // true
console.log(list.map((x) => x) instanceof TaggedList); // true (species)
console.log(list.slice() instanceof TaggedList); // true (species)
console.log(list.toSorted() instanceof TaggedList); // false
console.log(list.toReversed().constructor === Array); // true
console.log(Array.isArray(list.with(0, 9))); // trueA subclass whose Symbol.species getter throws shows that the new methods never read it:
class Guarded extends Array {
static get [Symbol.species]() {
throw new Error("species was read");
}
}
const g = Guarded.from([2, 1]);
console.log(g.toSorted()); // [1, 2]
try {
g.map((x) => x);
} catch (err) {
console.log(err.message); // "species was read"
}| Method | Builds its result with | Subclass instance in, what comes out |
|---|---|---|
| `map`, `filter`, `slice`, `concat`, `flat`, `flatMap` | `ArraySpeciesCreate` | Subclass (by default) |
| `splice` (the removed elements) | `ArraySpeciesCreate` | Subclass (by default) |
| `toSorted`, `toReversed`, `toSpliced`, `with` | `ArrayCreate` | Plain `Array` |
The reasoning behind the design
Symbol.species added complexity to every method that uses it. Each call has to look up a user-controlled constructor, which slows engines down. That lookup has also caused security bugs in engines, because user code runs in the middle of a built-in operation. TC39 has since treated species as a feature it would rather not extend, and the Change Array by Copy proposal left it out on purpose. In return you get a predictable result: the output is a plain, ordinary array no matter what you started with.
Typed arrays follow the same rule in their own way. Uint8Array.prototype.toSorted returns a new array of the same typed-array kind, and it also ignores species. The typed arrays chapter covers this in detail.
Getting your subclass back
If you need a subclass instance, rewrap the result explicitly. Because the conversion is visible in the code, readers can see what type they get:
class TaggedList extends Array {
sortedCopy(compare) {
return TaggedList.from(this.toSorted(compare));
}
}
const list = TaggedList.from([3, 1, 2]);
const sorted = list.sortedCopy((a, b) => a - b);
console.log(sorted instanceof TaggedList); // true
console.log([...sorted]); // [1, 2, 3]
console.log([...list]); // [3, 1, 2]from works here because it constructs the subclass through this, not through species.
Decision guide
- Use the generic
callform when you have an indexed array-like such asarguments, aNodeList, or a string, and you want a sorted, reversed, or edited copy in a single step. - Use
Array.fromor spread first when the source is iterable but not indexed (Set,Map, generators). The same applies when you want the iterator's view of a string, which keeps code points such as emoji intact. - Rewrap with
Subclass.from(...)when downstream code depends on subclass methods. - Treat an empty array from a generic call as a possible bug, not a valid answer, whenever the input type is uncertain.
Exercise
What does each line print? (1) Array.prototype.toSorted.call({ 1: "b", 0: "a" }) (2) Array.prototype.toSpliced.call({ length: 2, 0: "x" }, 0, 0, "w") (3) Array.prototype.with.call(null, 0, 1)
Show answer
(1) [] because there is no length property, so the length is 0. (2) ["w", "x", undefined] because the length is 2, index 1 is missing and is read as undefined, and "w" is inserted at the front. (3) It throws a TypeError, because ToObject cannot convert null.
Exercise
You have class Matrix extends Array with a custom method det(). A colleague writes m.toReversed().det() and gets "det is not a function". Explain why, and give a one-line fix.
Show answer
toReversed builds its result with ArrayCreate and ignores Symbol.species, so the result is a plain Array without det. Fix: Matrix.from(m.toReversed()).det(). Matrix.from constructs through this, so it returns a Matrix.
Exercise
Why is Array.prototype.toSorted.call(new Map([[2, "b"], [1, "a"]])) an empty array, and how would you get the entries sorted by key?
Show answer
The generic method reads length and numeric indices. A Map has neither, so the length is 0. Convert through the iterator first: [...map].toSorted((a, b) => a[0] - b[0]), which gives [[1, "a"], [2, "b"]].