Your product could be here, in front of thousands of JavaScript developers. Sponsor this spot →
JavaScript Quiz

Why does reduce throw on an empty array?

Do you know what will be the output of this code?

JavaScript
console.log([].reduce((a, b) => a + b));
Show answer and explanation

The answer is TypeError: Reduce of empty array with no initial value.

Without an initial value, reduce uses the first item as the accumulator. An empty array has no first item. Pass one as the second argument: .reduce((a, b) => a + b, 0).

Take the full quiz Next question →

More Arrays questions

  1. Why does [33, 2, 8].sort() not sort numbers correctly?
  2. What happens when you assign past the end of a JavaScript array?
  3. Why does [1, 2, 3].map(parseInt) return [1, NaN, NaN]?
  4. What does Array.push() return in JavaScript?
  5. How do you remove duplicates from an array with Set?

Related topics