Sub topic 13
How holes in sparse arrays are handled
This chapter assumes you know what array indices and length are, that you have used sort and splice, and that you have met toSorted, toSpliced, and with in earlier chapters. It covers one narrow rule with practical effects: the copying methods never produce holes. Any hole they read comes out as a real undefined element.
What a hole is
A sparse array has fewer elements than its length suggests. The missing positions are called holes. A hole differs from an element whose value is undefined. At a hole, the index does not exist as a property at all.
const sparse = [3, , 1];
const dense = [3, undefined, 1];
console.log(sparse.length, dense.length); // 3 3
console.log(sparse[1], dense[1]); // undefined undefined
console.log(1 in sparse); // false
console.log(1 in dense); // true
console.log(Object.keys(sparse)); // ["0", "2"]
console.log(Object.keys(dense)); // ["0", "1", "2"]Reading sparse[1] gives undefined because property lookup on a missing key gives undefined. That makes holes easy to miss: bracket access cannot tell the two arrays apart. Only in, Object.hasOwn, or Object.keys can.
Holes usually show up by accident. These are the common sources:
new Array(5)creates a length-5 array with five holes.- Assigning past the end, as in
arr[10] = xon a short array, fills the gap with holes. delete arr[i]removes the property and leaves a hole in its place.- Increasing
arr.lengthdirectly adds holes at the end. - A stray comma in a literal, such as
[1, , 2], creates a hole.
The rule: holes read as undefined, results are always dense
Each copying method builds its result by walking indices from 0 to length - 1. At each index it does a plain property read, which the spec calls Get. It does not check whether the property exists first. A hole therefore reads as undefined, and that undefined is written into the new array as an actual element.
The older mutating methods work differently. sort, reverse, and splice check HasProperty before moving a value. When the check fails they delete the target index instead of writing to it, so the holes survive.
toSorted next to sort
const a = [3, , 1];
const b = [3, , 1];
b.sort();
console.log(b); // [1, 3, <1 empty item>]
console.log(2 in b); // false
const sorted = a.toSorted();
console.log(sorted); // [1, 3, undefined]
console.log(2 in sorted); // true
console.log(a); // [3, <1 empty item>, 1] (unchanged, still sparse)Both methods move the missing value to the end, but they leave different things there. sort keeps a hole. toSorted writes undefined. The original array is not changed, so its hole is still there.
The sort algorithm handles undefined in a special way. Every undefined value goes to the end and is never passed to your comparator. That's why a numeric comparator like (a, b) => a - b does not produce NaN comparisons for holes:
const calls = [];
const result = [5, , 2, undefined].toSorted((x, y) => {
calls.push([x, y]);
return x - y;
});
console.log(result); // [2, 5, undefined, undefined]
console.log(calls.flat().includes(undefined)); // falseThe hole and the explicit undefined give the same output. In the result you cannot tell which one came from a hole.
with next to index assignment
const values = [3, , 1];
console.log(values.with(0, 9)); // [9, undefined, 1]
console.log(1 in values.with(0, 9)); // true
const copy = [...values]; // spread also densifies
copy[0] = 9;
console.log(1 in copy); // truewith copies every index, and holes come out as undefined. You can also pass the index of a hole to with. That fills the hole in the copy and leaves every other index as it was:
console.log([3, , 1].with(1, 2)); // [3, 2, 1]toSpliced next to splice
const a = [1, , 3, 4];
const b = [1, , 3, 4];
b.splice(0, 1);
console.log(b); // [<1 empty item>, 3, 4]
console.log(0 in b); // false
const spliced = a.toSpliced(0, 1);
console.log(spliced); // [undefined, 3, 4]
console.log(0 in spliced); // truesplice shifted the hole down one place and kept it a hole. toSpliced turned it into undefined. Holes that fall inside the deleted range are simply dropped, as you would expect. Only holes that survive into the result become undefined.
toReversed next to reverse
console.log([1, , 3].reverse()); // [3, <1 empty item>, 1]
console.log([1, , 3].toReversed()); // [3, undefined, 1]Summary table
| Operation on `[3, , 1]` | Result | Hole kept? |
|---|---|---|
| `sort()` | `[1, 3, <empty>]` | Yes |
| `toSorted()` | `[1, 3, undefined]` | No |
| `reverse()` | `[1, <empty>, 3]` | Yes |
| `toReversed()` | `[1, undefined, 3]` | No |
| `splice(0, 1)` (mutates) | `[<empty>, 1]` | Yes |
| `toSpliced(0, 1)` | `[undefined, 1]` | No |
| `with(0, 9)` | `[9, undefined, 1]` | No |
| `slice()` | `[3, <empty>, 1]` | Yes |
| `[...arr]` / `Array.from(arr)` | `[3, undefined, 1]` | No |
slice behaves like the old methods and keeps holes. Spread and Array.from go through the iterator, which also reads with Get, so they densify the same way the ES2023 methods do. That is why the [...arr].sort() fallback from the support chapter gives the same result as arr.toSorted() even for sparse input. The spread fills the holes before sort ever sees them.
Why this matters in practice
Callbacks start running for positions they used to skip
forEach, map, filter, some, and every skip holes. They do not skip undefined elements. So if you swap sort() for toSorted() and then pass the result to a callback, the callback can now be called with values it was never called with before.
const people = [{ name: "Ada" }, , { name: "Linus" }];
const viaSort = people.slice().sort((a, b) => a.name.localeCompare(b.name));
console.log(viaSort.map((p) => p.name)); // ["Ada", "Linus", <1 empty item>]
const viaToSorted = people.toSorted((a, b) => a.name.localeCompare(b.name));
try {
viaToSorted.map((p) => p.name);
} catch (err) {
console.log(err instanceof TypeError); // true: p is undefined
}The comparator was safe in both cases because sorting never passes undefined to it. The map afterward is what fails.
Lengths stay the same, but counts change
The result always has the same length as the input (adjusted for toSpliced). What changes is the number of real elements. Code that counts with Object.keys(arr).length, or that uses in to check whether an entry exists, will get different answers after a copying method runs.
const arr = new Array(3);
arr[1] = "x";
console.log(Object.keys(arr).length); // 1
console.log(Object.keys(arr.toSorted()).length); // 3Prototype values can leak in
Get follows the prototype chain, so a hole reads whatever the prototype has at that index. This edge case comes up rarely, but it shows that "hole becomes undefined" is really "hole becomes whatever a normal read returns".
const proto = Object.create(Array.prototype);
proto[1] = "from prototype";
const arr = [1, , 3];
Object.setPrototypeOf(arr, proto);
console.log(arr.with(0, 9)); // [9, "from prototype", 3]
console.log(arr.slice()); // [1, <1 empty item>, 3]slice checks HasProperty first. That check also follows the prototype chain, so slice copies the inherited value too. Run it in Node and you will see [1, "from prototype", 3] for slice as well. The last comment above shows what you would get without the prototype entry. The point that matters is that the copying methods write an own property for every index, so the result never depends on its prototype afterward.
Exercises
Exercise
What does [ , 2, , 1].toSorted() return, and how many own index properties does the result have? How does that differ from calling .sort() on the same array?
Show answer
toSorted() returns [1, 2, undefined, undefined] with four own index properties (Object.keys gives 4 keys). .sort() changes the array to [1, 2, <2 empty items>], which has only two own index properties, because sort keeps holes at the end instead of writing undefined.
Exercise
Given const a = new Array(3);, what do a.with(1, "x") and a.with(1, "x").map((v) => typeof v) return?
Show answer
a.with(1, "x") returns [undefined, "x", undefined], a dense array. Because every index now exists, map calls the callback three times and returns ["undefined", "string", "undefined"]. Calling map on the original a would call the callback zero times and return [<3 empty items>].
Exercise
A codebase replaces list.splice(i, 1); list.forEach(render); with const next = list.toSpliced(i, 1); next.forEach(render);. The list sometimes comes from new Array(n) that was only partly filled. What changes, and how would you keep the old behavior?
Show answer
splice kept unfilled slots as holes, which forEach skipped. toSpliced turns them into undefined elements, so render is now called with undefined for each unfilled slot. To keep the old behavior, filter before rendering (next.filter((x) => x !== undefined).forEach(render)), or have render skip undefined. A better fix is to stop creating sparse lists in the first place, for example with Array.from({ length: n }, () => null) and explicit placeholders.