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

Sarah

TypeError. reduce can’t “pick a first accumulator” from an empty array unless you hand it an initial value, so it throws (Reduce of empty array with no initial value) and console.log never runs.

It’s like trying to start a tally with no first number on the whiteboard — give it a starting 0 and you’ll get 0 back.

reduce() blows up on an empty array unless you give it an initial accumulator, so you get “Reduce of empty array with no initial value” and the console.log never happens.

Treat it like a tally: start from 0, and an empty list sensibly reduces to 0 instead of throwing.

Look — this is why I default to always passing an initial value to reduce, even when I “know” the array won’t be empty. The one time it’s empty in prod, you get an exception instead of a boring 0 and your logging/metrics never fire.

Yeah, that’s how you get paged at 2am over an empty array. i’ve seen “can’t happen” turn into “happened once” because an upstream filter changed, and reduce without an init value just faceplants.