Sub topic 7
Choosing an Initial Value and Handling Empty Arrays
This chapter assumes you already know how reduce calls its callback with an accumulator and the current element. Here the focus is the second argument to reduce, the initial value. That argument decides the accumulator's starting type, which element the callback sees first, and what happens when the array is empty.
What Changes When You Omit the Initial Value
When you pass an initial value, the accumulator starts as that value and the callback runs once for every element, starting at index 0.
When you omit it, reduce uses the first element as the accumulator and starts calling the callback at index 1. That shortcut has three effects:
| Array length | With initial value | Without initial value |
|---|---|---|
| 0 | Returns the initial value, callback never runs | Throws `TypeError` |
| 1 | Callback runs once | Returns the single element, callback never runs |
| 2 or more | Callback runs `length` times | Callback runs `length - 1` times |
const add = (acc, n) => acc + n;
console.log([5].reduce(add)); // 5 (callback never called)
console.log([].reduce(add, 0)); // 0
try {
[].reduce(add);
} catch (err) {
console.log(err.message); // "Reduce of empty array with no initial value"
}The empty-array error is the one that reaches production. Data that came from a filter, an API response, or a search often turns out empty, and code that worked in testing throws as soon as it does.
The Type Mismatch Bug
Leaving out the initial value also means the accumulator starts as whatever type the elements are. When you reduce objects into a number, that type is wrong:
const orders = [{ total: 50 }, { total: 20 }, { total: 80 }];
const broken = orders.reduce((sum, order) => sum + order.total);
console.log(broken); // "[object Object]2080"
const fixed = orders.reduce((sum, order) => sum + order.total, 0);
console.log(fixed); // 150In the broken version, the first sum is the object { total: 50 }. Adding a number to an object converts both to strings, and that string carries through every later step. No error is thrown. You just get a wrong result.
Picking the Right Initial Value
A good initial value is the identity for your operation: a value that leaves the result unchanged when combined with an element. It is also the correct answer for an empty array.
| Operation | Initial value | Why |
|---|---|---|
| Sum | `0` | `x + 0 === x` |
| Product | `1` | `x * 1 === x` |
| String join | `''` | `s + '' === s` |
| Collect into array | `[]` | Nothing collected yet |
| Build a lookup or group | `{}` or `new Map()` | No keys yet |
| Maximum | `-Infinity` | Every number is larger |
| Minimum | `Infinity` | Every number is smaller |
Maximum and minimum need more thought. -Infinity may not be a sensible answer for "the highest price in an empty cart." In that case, handle the empty case on purpose instead of letting a sentinel value leak out:
function maxPrice(items) {
if (items.length === 0) return null;
return items.reduce((max, item) => Math.max(max, item.price), -Infinity);
}
console.log(maxPrice([{ price: 3 }, { price: 9 }])); // 9
console.log(maxPrice([])); // nullMutable Initial Values
When the initial value is an object or an array, it is created once and passed along through every step. Write it as a literal inside the call, such as reduce(fn, {}). Don't pass a shared variable, because reduce will mutate it and the changes will show up wherever else that object is used.
Exercise
What does ['a', 'b', 'c'].reduce((acc, s) => acc + s.toUpperCase()) return, and why? How would you fix it?
Show answer
It returns 'aBC'. Without an initial value, the first element 'a' becomes the accumulator and is never passed to the callback, so it is never uppercased. Pass '' as the initial value: .reduce((acc, s) => acc + s.toUpperCase(), '') returns 'ABC'.
Exercise
A function computes the average with scores.reduce((a, b) => a + b) / scores.length. What happens when scores is empty, and how should you rewrite it?
Show answer
It throws a TypeError because reduce has no initial value. Adding 0 as the initial value would give 0 / 0, which is NaN. Check for the empty case first, for example if (scores.length === 0) return null;, then return scores.reduce((a, b) => a + b, 0) / scores.length.