Interview Q&A / JavaScript

BeginnerQuick answer1 min readUpdated 3 Oct 2026

How does Array.reduce work, and why should you give it an initial value?

SHORT ANSWER

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

js
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: 0

What 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.

#javascript#arrays#reduce

Related questions

Practise more JavaScript questions

Test your recall with short answers, then return to the detailed explanations when you need context.

Open JavaScript quick answers →

Get new questions like this by email

One short email when something new and useful lands. No spam, unsubscribe in one tap.

By subscribing you agree to the Privacy Policy.