#47: [].reduce(...) with no initial value
Topic: arrays · Difficulty: ★★★
try {
[].reduce((acc, x) => acc + x);
} catch (e) {
console.log(e.message);
}Output
Reduce of empty array with no initial value
Why
When reduce() is called without an initial value, its normal behavior is to use the array's first element as the starting accumulator and begin invoking the callback from the second element onward. On an empty array there is no first element to fall back on and nothing for the callback to ever process, so the specification mandates that reduce() throws a TypeError rather than silently returning undefined or 0. This is a well-known gotcha: reduce over a possibly-empty array is only safe when you always pass an explicit initial value, e.g. arr.reduce((acc, x) => acc + x, 0), which sidesteps the empty-array case entirely.