Sub topic 17
Edge Cases and Common Pitfalls
This chapter assumes you know the core array methods covered earlier: map, filter, reduce, sort, the search methods, and the ES2023 copying methods. The focus here is on where those methods behave in ways you might not expect. The three biggest sources of bugs are sparse arrays, reduce without an initial value, and the default sort order. A few smaller traps related to callbacks and equality come at the end.
Sparse Arrays and Holes
A sparse array is an array with holes. A hole is an index below length that has no element at all. A hole is different from a slot that holds undefined. The slot simply does not exist.
You can create holes in several ways, some of them by accident:
const literal = [1, , 3]; // hole at index 1
const sized = Array(3); // three holes
const grown = ['a'];
grown[3] = 'd'; // holes at indexes 1 and 2
const deleted = ['x', 'y', 'z'];
delete deleted[1]; // hole at index 1
console.log(literal.length); // 3
console.log(1 in literal); // false (no element at index 1)
console.log(1 in [1, undefined, 3]); // true (element exists, value is undefined)
console.log(grown); // [ 'a', <2 empty items>, 'd' ] in Node.js
console.log(deleted.length); // 3 (delete does not shift or shrink)How methods treat holes
Older methods (ES5 and earlier) skip holes. Newer features (ES2015 and later) treat holes as undefined. This split explains most of the surprises.
const sparse = [1, , 3];
// Skip holes: callback never runs for index 1
sparse.forEach((x, i) => console.log(i, x)); // 0 1, then 2 3
console.log(sparse.map(x => x * 2)); // [ 2, <1 empty item>, 6 ]
console.log(sparse.filter(() => true)); // [1, 3]
console.log(sparse.reduce((a, b) => a + b)); // 4
console.log(Object.keys(sparse)); // ['0', '2']
// Treat holes as undefined
for (const x of sparse) console.log(x); // 1, undefined, 3
console.log([...sparse]); // [1, undefined, 3]
console.log(sparse.find(x => x === undefined)); // undefined (it did visit index 1)
console.log(sparse.findIndex(x => x === undefined)); // 1
console.log(sparse.includes(undefined)); // true
console.log(sparse.indexOf(undefined)); // -1 (indexOf skips holes)
console.log(sparse.toSorted()); // [1, 3, undefined]
console.log(Array.from(sparse)); // [1, undefined, 3]| Behavior | Methods and features |
|---|---|
| Skip holes | `forEach`, `map` (keeps the hole), `filter` (drops the hole), `reduce`, `some`, `every`, `indexOf`, `Object.keys` |
| Treat holes as `undefined` | `for...of`, spread, `find`, `findIndex`, `findLast`, `includes`, `Array.from`, `toSorted`, `toReversed`, `toSpliced`, `with` |
| Other | `join` writes holes as empty strings, `JSON.stringify` writes them as `null`, `sort` moves them to the end |
The `Array(n).map` trap
A common mistake is trying to generate a sequence from Array(n):
console.log(Array(3).map((_, i) => i)); // [ <3 empty items> ]
console.log(Array.from({ length: 3 }, (_, i) => i)); // [0, 1, 2]
console.log(Array(3).fill(0).map((_, i) => i)); // [0, 1, 2]
console.log([...Array(3)].map((_, i) => i)); // [0, 1, 2]map skips every hole, so the callback never runs. Array.from, fill, and spread all produce real undefined elements first, so map has something to visit.
reduce Without an Initial Value
When you omit the initial value, reduce uses the first element as the accumulator and starts the callback at index 1. That shortcut causes three distinct problems.
Problem 1: empty arrays throw
try {
[].reduce((a, b) => a + b);
} catch (err) {
console.log(err instanceof TypeError); // true
console.log(err.message); // Reduce of empty array with no initial value (V8 wording)
}
console.log([].reduce((a, b) => a + b, 0)); // 0This bug often stays hidden in testing because the test data is never empty. It shows up in production after a filter upstream returns no matches.
Problem 2: the accumulator has the wrong type
const cart = [{ price: 5 }, { price: 10 }];
const wrong = cart.reduce((sum, item) => sum + item.price);
console.log(wrong); // '[object Object]10'
const right = cart.reduce((sum, item) => sum + item.price, 0);
console.log(right); // 15Without 0, the first accumulator is the object { price: 5 }. Adding a number to an object converts the object to a string.
Problem 3: single elements skip your logic
const result = [{ price: 5 }].reduce((sum, item) => sum + item.price);
console.log(result); // { price: 5 } (callback never ran)Default Sort Order
Called without a comparator, sort converts every element to a string and compares the strings by UTF-16 code units. Numbers therefore sort by their digits, not by their numeric value.
console.log([10, 1, 5, 100].toSorted()); // [1, 10, 100, 5]
console.log([10, 1, 5, 100].toSorted((a, b) => a - b)); // [1, 5, 10, 100]
// Uppercase letters come before lowercase in code-unit order
console.log(['banana', 'apple', 'Cherry'].toSorted()); // ['Cherry', 'apple', 'banana']
console.log(['banana', 'apple', 'Cherry'].toSorted((a, b) => a.localeCompare(b)));
// ['apple', 'banana', 'Cherry']
// undefined always goes last, and the comparator is never called for it
console.log([3, undefined, 1].toSorted((a, b) => a - b)); // [1, 3, undefined]Boolean comparators
A comparator must return a negative number, zero, or a positive number. A comparison like a > b returns true or false, which become 1 and 0. It never signals "a comes first", so the result depends on the engine's algorithm and on the input order.
const bad = (a, b) => a > b; // unreliable: never returns a negative number
const good = (a, b) => a - b; // numbers
const goodGeneric = (a, b) => (a > b) - (a < b); // returns -1, 0, or 1 for any comparable values
console.log([3, 1, 2].toSorted(good)); // [1, 2, 3]
console.log([3, 1, 2].toSorted(goodGeneric)); // [1, 2, 3]Also keep in mind that sort mutates and returns the same array. const sorted = arr.sort() gives you two names for one reordered array. Use toSorted when you need to keep the original.
Smaller Traps
Callbacks receive more arguments than you think
Array methods pass (element, index, array) to the callback. Functions that take optional extra parameters will receive those extra arguments too.
console.log(['1', '2', '3'].map(parseInt)); // [1, NaN, NaN]
// parseInt('2', 1) and parseInt('3', 2) are invalid radix calls
console.log(['1', '2', '3'].map(s => parseInt(s, 10))); // [1, 2, 3]
console.log(['1', '2', '3'].map(Number)); // [1, 2, 3]NaN and object equality
indexOf uses strict equality, where NaN !== NaN. includes uses SameValueZero, which treats NaN as equal to itself. Both compare objects by reference, not by contents.
console.log([NaN].indexOf(NaN)); // -1
console.log([NaN].includes(NaN)); // true
console.log([[1]].includes([1])); // false (different array objects)
console.log([1, 2] === [1, 2]); // false
const target = { id: 2 };
const list = [{ id: 1 }, target];
console.log(list.includes(target)); // true (same reference)
console.log(list.some(item => item.id === 2)); // true (compare by property)Writing to length
Assigning to length changes the array. Shrinking it deletes elements for good, and growing it adds holes.
const items = [1, 2, 3, 4];
items.length = 2;
console.log(items); // [1, 2]
items.length = 4;
console.log(items); // [ 1, 2, <2 empty items> ]forEach ignores return values and awaits
return inside a forEach callback only ends that one call, and break is a syntax error there. forEach also does not wait for promises returned by an async callback. Use for...of when you need to stop early or run steps in order with await.
Exercise
What does [5, , 7].map(x => x + 1) return, and how does that differ from [...[5, , 7]].map(x => x + 1)?
Show answer
The first returns [6, <1 empty item>, 8] because map skips the hole and keeps it in the result. The second returns [6, NaN, 8], because spread turns the hole into undefined and undefined + 1 is NaN.
Exercise
const total = items.filter(i => i.inStock).reduce((s, i) => s + i.price); works in testing but crashes in production with a TypeError. Why, and what is the fix?
Show answer
When no items are in stock, filter returns an empty array, and reduce with no initial value throws on an empty array. With exactly one item in stock it would return the item object instead of a number. Pass 0 as the initial value: .reduce((s, i) => s + i.price, 0).
Exercise
Why is scores.sort((a, b) => a > b) a bug, and what should replace it for an array of numbers?
Show answer
The comparator returns true or false (1 or 0) and never a negative number, so the sort cannot reliably tell that a should come first. The order then depends on the engine and the input. Use (a, b) => a - b, and use toSorted if the original array must stay unchanged.