JS Quiz: Medium: Reduce accumulator initialization edge case

What happens here?

const arr = [];
const total = arr.reduce((sum, n) => sum + n);
console.log(total);
  • 0
  • undefined
  • NaN
  • TypeError
0 voters

Hari :slightly_smiling_face:

TypeError — reduce on an empty array with no initial accumulator throws immediately, so it never even gets to your callback.

It’s like trying to start a running total without a starting number. Give it an initial value and you get what you probably expected: [].reduce((sum, n) => sum + n, 0) → 0.

I’d pick “TypeError” here — reduce on an empty array with no initial value throws immediately, so your callback never runs.

It’s like starting a running total with no starting number. [].reduce((sum, n) => sum + n, 0) gives you 0, which is usually what people expect.