Sub topic 7
Choosing an Initial Value and Handling Empty Arrays
This chapter assumes you know how reduce works: it takes a callback with an accumulator and the current element, and it returns whatever the last callback call returned. Here the focus is on the optional second argument to reduce, the initial value. That argument decides the starting accumulator, how many times your callback runs, what type flows through the reduction, and whether an empty array returns a value or throws.
Two Ways to Start a Reduction
reduce behaves in one of two ways, depending on whether you pass an initial value.
- With an initial value, the accumulator starts as that value and the callback runs once for every element, starting at index 0.
- Without an initial value, the accumulator starts as the first element and the callback runs once for every element after it, starting at index 1.
You can see the difference by counting callback calls:
let calls = 0;
const sumNoInit = [10, 20, 30].reduce((acc, n) => {
calls++;
return acc + n;
});
console.log(sumNoInit, calls); // 60 2
calls = 0;
const sumWithInit = [10, 20, 30].reduce((acc, n) => {
calls++;
return acc + n;
}, 0);
console.log(sumWithInit, calls); // 60 3For a sum of numbers, both versions give the same answer. The cases where they differ are the subject of this chapter: empty arrays, single-element arrays, and reductions where the accumulator's type differs from the element's type.
The Empty Array Problem
Calling reduce on an empty array without an initial value throws, because there is no element to use as the starting accumulator:
try {
[].reduce((acc, n) => acc + n);
} catch (err) {
console.log(err.name); // TypeError
console.log(err.message); // e.g. "Reduce of empty array with no initial value"
}
console.log([].reduce((acc, n) => acc + n, 0)); // 0The exact message varies by engine, but every engine throws a TypeError. The bug is easy to miss because test data is rarely empty. Production data often is: a search with no results, a cart with no items, a filter step that removed everything. A pipeline like items.filter(...).reduce(...) without an initial value works for months and then crashes the first time the filter matches nothing.
The Type Mismatch Problem
Without an initial value, the first element becomes the accumulator. That only works when the accumulator and the elements have the same type. When they don't, you get wrong results instead of an error:
const orders = [{ total: 50 }, { total: 20 }];
const broken = orders.reduce((sum, order) => sum + order.total);
console.log(broken); // '[object Object]20'
const fixed = orders.reduce((sum, order) => sum + order.total, 0);
console.log(fixed); // 70In the broken version, sum starts as the object { total: 50 }. Adding a number to an object converts the object to the string '[object Object]', and + becomes string concatenation.
The single-element case is worse, because it hides the bug:
const one = [{ total: 50 }];
console.log(one.reduce((sum, order) => sum + order.total)); // { total: 50 }The callback never runs, so reduce returns the object itself instead of the number 50. Nothing throws, and the wrong type moves on to the next part of your program.
The rule that follows: if the result's type differs from the element's type, you must pass an initial value. Sums over object fields, counts, grouping into objects, and building arrays or Maps all fall into this category.
Picking the Right Initial Value
A good initial value is the identity of your combining operation. An identity value leaves any other value unchanged when combined with it: x + 0 is x, and x * 1 is x. Starting with the identity means an empty array produces a sensible "nothing here" result, and a non-empty array is unaffected by the starting point.
| Goal | Combining step | Initial value | Empty array result | Column | Column |
|---|---|---|---|---|---|
| Sum | `acc + n` | `0` | `0` | ||
| Product | `acc * n` | `1` | `1` | ||
| Join strings | `acc + s` | `''` | `''` | ||
| Collect into array | `[...acc, x]` or `acc.push(x)` | `[]` | `[]` | ||
| Build lookup object | `acc[key] = ...` | `{}` | `{}` | ||
| Build a Map | `acc.set(key, ...)` | `new Map()` | empty Map | ||
| All match | `acc && test(x)` | `true` | `true` | ||
| Any match | `acc \ | \ | test(x)` | `false` | `false` |
| Maximum | `Math.max(acc, n)` | `-Infinity` | `-Infinity` | ||
| Minimum | `Math.min(acc, n)` | `Infinity` | `Infinity` |
The "all match" and "any match" rows follow the same logic as every and some, which return true and false for empty arrays. A later chapter covers those methods.
When No Identity Makes Sense
Maximum and minimum have identity values, but -Infinity is often a poor answer to "what is the highest price in an empty list?" Code that displays or stores it will show something meaningless. In these cases, decide what "no answer" should look like and write it down in code:
function maxOrUndefined(nums) {
return nums.reduce(
(max, n) => (max === undefined || n > max ? n : max),
undefined
);
}
console.log(maxOrUndefined([3, 9, 4])); // 9
console.log(maxOrUndefined([])); // undefinedThis version always passes an initial value, so it never throws. It also returns undefined when there is nothing to compare, which callers can check for.
An average has no identity value. An empty array has no meaningful average, and a naive calculation produces 0 / 0, which is NaN. Guard it directly:
function average(nums) {
if (nums.length === 0) return null;
const total = nums.reduce((sum, n) => sum + n, 0);
return total / nums.length;
}
console.log(average([2, 4, 6])); // 4
console.log(average([])); // nullEdge Cases Worth Knowing
Passing `undefined` Still Counts
reduce checks how many arguments you passed, not whether the second one is undefined. An explicit undefined is a real initial value:
console.log([].reduce((a, b) => a + b, undefined)); // undefined (no error)This is why maxOrUndefined above works. It also means a wrapper that forwards an optional parameter changes behavior:
const sumAll = (nums, init) => nums.reduce((a, b) => a + b, init);
console.log(sumAll([1, 2, 3])); // NaN, because undefined + 1 is NaNinit is always forwarded, even when it is undefined, so the reduction starts from undefined. Give the parameter a default (init = 0) or don't forward it.
Sparse Arrays
reduce skips holes in sparse arrays. Without an initial value, the accumulator starts at the first present element, not at index 0. An array made only of holes behaves like an empty array:
console.log([, 5, ,].reduce((a, b) => a + b)); // 5 (only one present element)
try {
[, ,].reduce((a, b) => a + b);
} catch (err) {
console.log(err instanceof TypeError); // true
}So arr.length > 0 is not a complete guard for the no-initial-value form. Passing an initial value covers this case as well.
Shared Mutable Initial Values
Passing an object or array as the initial value is common, and mutating it inside the callback is a reasonable choice for performance. The problem starts when that object is created once and reused across calls:
const emptyCounts = {};
function countWordsBuggy(words) {
return words.reduce((counts, w) => {
counts[w] = (counts[w] ?? 0) + 1;
return counts;
}, emptyCounts);
}
console.log(countWordsBuggy(['a', 'b'])); // { a: 1, b: 1 }
console.log(countWordsBuggy(['a'])); // { a: 2, b: 1 } (state leaked)
function countWords(words) {
return words.reduce((counts, w) => {
counts[w] = (counts[w] ?? 0) + 1;
return counts;
}, {});
}
console.log(countWords(['a', 'b'])); // { a: 1, b: 1 }
console.log(countWords(['a'])); // { a: 1 }Write the object or array literal inline in the reduce call, so each call to the function creates a fresh accumulator.
reduceRight Follows the Same Rules
reduceRight walks from the last index toward the first. Without an initial value, it starts from the last present element and throws on an empty array, exactly like reduce.
A Practical Rule of Thumb
Always pass an initial value unless all of these are true:
- The accumulator has the same type as the elements.
- The array is guaranteed to have at least one present element.
- No identity value exists, or the identity value would be misleading.
Leaving out the initial value is safe only when all three hold, and that is rare. Passing one costs a few characters. It also tells the reader what type the reduction produces and what an empty input returns.
Exercise
A teammate writes const longest = names.filter(n => n.startsWith(prefix)).reduce((a, b) => (b.length > a.length ? b : a));. Describe two inputs that make it fail or misbehave, and rewrite it so it returns '' when no name matches.
Show answer
If no name starts with prefix, filter returns an empty array and reduce throws a TypeError because there is no initial value. If names is a sparse array whose matching entries are all holes, it also throws. (A single match works correctly, because the element and accumulator types are both strings.) Rewrite: const longest = names.filter(n => n.startsWith(prefix)).reduce((a, b) => (b.length > a.length ? b : a), ''); The empty string has length 0, so any real match replaces it, and an empty result returns ''.
Exercise
What does each line print, and why? (1) console.log([7].reduce((a, b) => a * b * 100)); (2) console.log([].reduce((a, b) => a + b, undefined)); (3) console.log([{ n: 2 }, { n: 3 }].reduce((acc, o) => acc + o.n));
Show answer
(1) 7: a single element with no initial value is returned without calling the callback. (2) undefined: an explicitly passed undefined counts as an initial value, so the empty array returns it instead of throwing. (3) '[object Object]3': the accumulator starts as the first object, and adding a number to an object converts it to a string and concatenates. Passing 0 as the initial value would give 5.
Exercise
Write a function indexById(items) that uses reduce to turn an array of { id, ... } objects into a Map keyed by id. It must return an empty Map for an empty array, and calling it twice must never share state.
Show answer
function indexById(items) { return items.reduce((map, item) => map.set(item.id, item), new Map()); } Map.prototype.set returns the Map, so the callback returns the accumulator. Creating new Map() inline makes a fresh accumulator on every call, and an empty array returns that empty Map.