Skip to content

TypeError: Reduce of empty array with no initial value

Error message

                Reduce of empty array with no initial value
              

Quick summary

You called array.reduce() on an empty array without a second argument (initial value) — reduce has nothing to start with.

Why this happens

  • Called reduce() on an empty array without an initial value

  • The array was unexpectedly empty due to a filter or data issue

  • Forgot to pass the initial value as the second argument to reduce

Minimal example

✗ Broken code
const nums = [];
const total = nums.reduce((a, b) => a + b);
✓ Fixed code
const nums = [];
const total = nums.reduce((a, b) => a + b, 0);

An empty array with no initial value has nothing to reduce. Pass 0 as the initial value to get 0 for empty arrays.

How to diagnose

  • Check if the array is empty before calling reduce

  • Log the array length to confirm it is empty

  • Verify the second argument (initial value) is provided

How to fix

  • Always provide an initial value as the second argument to reduce

  • Check if the array is empty and provide a default result

  • Use arr.length > 0 ? arr.reduce(fn) : defaultValue

How to prevent

  • Always pass an initial value to reduce: arr.reduce(fn, initialValue)

  • Validate array contents before reducing

Related Resources

Related Glossary

Related Lessons

Related Practice

← Back to language