Sub topic 17
Edge Cases and Common Pitfalls
This chapter assumes you already know map, filter, reduce, sort, and the difference between methods that mutate an array and methods that copy it. It covers three behaviors that cause bugs even in experienced developers' code: holes in sparse arrays, reduce called without an initial value, and the default string order of sort.
Sparse Arrays Have Holes, Not undefined
A sparse array has indexes with no element at all. These missing slots are called holes. You get holes from Array(n), from extra commas in a literal, from delete arr[i], or from assigning past the end of an array.
A hole is different from an element whose value is undefined, and array methods treat the two differently:
const sparse = [1, , 3];
console.log(sparse.length); // 3
console.log(1 in sparse); // false (no element at index 1)
sparse.forEach(x => console.log('forEach:', x)); // 1, then 3
for (const x of sparse) console.log('for...of:', x); // 1, undefined, 3
console.log(sparse.map(x => x * 2)); // [ 2, <1 empty item>, 6 ]
console.log(sparse.includes(undefined)); // true
console.log(sparse.indexOf(undefined)); // -1forEach, map, filter, reduce, some, and every skip holes. for...of, includes, find, and spread syntax treat a hole as undefined. As a result, the same array can look like it has 2 elements or 3, depending on which method you use to count them.
reduce Without an Initial Value
If you leave out the initial value, reduce uses the first element as the starting accumulator and begins the loop at the second element. That causes two problems.
// 1. An empty array throws
try {
[].reduce((sum, n) => sum + n);
} catch (err) {
console.log(err.message); // "Reduce of empty array with no initial value"
}
// 2. The accumulator starts as an object, not a number
const orders = [{ total: 40 }, { total: 15 }];
const wrong = orders.reduce((sum, o) => sum + o.total);
console.log(wrong); // "[object Object]15"
const right = orders.reduce((sum, o) => sum + o.total, 0);
console.log(right); // 55A one-element array without an initial value is also a trap. reduce returns that element and never calls your callback.
The fix is simple: always pass an initial value that has the same type as the result you want.
Default sort Compares Strings
When you call sort without a comparator, it converts each element to a string and compares the strings by UTF-16 code units. Any undefined values and holes are moved to the end.
console.log([10, 9, 1, 100].toSorted()); // [1, 10, 100, 9]
console.log([10, 9, 1, 100].toSorted((a, b) => a - b)); // [1, 9, 10, 100]
console.log(['b', 'a', 'B'].toSorted()); // ['B', 'a', 'b']
console.log(['b', 'a', 'B'].toSorted((a, b) => a.localeCompare(b))); // ['a', 'b', 'B']
// Broken comparator: it returns true or false, never a negative number
console.log([3, 1, 2].toSorted((a, b) => a > b)); // order not guaranteedA comparator must return a negative number, zero, or a positive number. A boolean converts to only 1 or 0, so the sort never sees "a comes first", and the order you get depends on the engine.
| Pitfall | Symptom | Fix |
|---|---|---|
| Holes from `Array(n)` or `delete` | `map` or `forEach` skips slots | `Array.from`, `fill`, `splice` |
| `reduce` with no initial value | TypeError, or wrong type | Always pass an initial value |
| `sort()` on numbers | `[1, 10, 9]` | `(a, b) => a - b` |
| Boolean comparator | Unstable order | Return a number |
| `sort()` on shared data | Original array changed | `toSorted()` |
Exercise
What does Array(3).map((_, i) => i) return, and how would you get [0, 1, 2] instead?
Show answer
It returns an array of 3 empty slots, [ <3 empty items> ], because map skips holes and never calls the callback. Use Array.from({ length: 3 }, (_, i) => i) or Array(3).fill(0).map((_, i) => i).
Exercise
Why does [{ n: 2 }, { n: 3 }].reduce((acc, x) => acc + x.n) return "[object Object]3", and what is the corrected call?
Show answer
With no initial value, the accumulator starts as the first object. Adding a number to an object converts the object to the string "[object Object]", so the + becomes string concatenation. The corrected call is .reduce((acc, x) => acc + x.n, 0), which returns 5.