How does Array.reduce work, and why should you give it an initial value?
reduce walks the array carrying an accumulator: each callback call gets the accumulator and the current item and returns the next accumulator. Without an initial value, an empty array throws a TypeError.
Explain it simply
Think of a cashier adding up a bill. The running total is the accumulator. Every item is added to it, and the total after the last item is the answer.
reduce(callback, initial) starts with initial as the accumulator and calls callback(acc, item) for each element. Whatever you return becomes the accumulator for the next round.
If you skip the initial value, the first element becomes the starting accumulator and the loop starts from the second. That is fine for a sum of a non-empty list, but an empty array then has no start and throws. An initial value also lets the result be a different type than the items, such as an object of counts.
Example
console.log([10, 20, 30].reduce((acc, n) => acc + n, 0)); // Output: 60
const counts = ["upi", "card", "upi"].reduce((acc, mode) => {
acc[mode] = (acc[mode] || 0) + 1;
return acc;
}, {});
console.log(counts); // Output: {"upi":2,"card":1}
try {
[].reduce((a, b) => a + b);
} catch (e) {
console.log(e.name); // Output: TypeError
}
console.log([].reduce((a, b) => a + b, 0)); // Output: 0What to say in the interview
"reduce folds an array into one value by passing an accumulator through the callback. I always supply an initial value: it makes empty arrays safe and lets me return an object or array instead of a number."
Common mistakes
- Forgetting to return the accumulator inside the callback, so the next round gets undefined.