Skip to content

How to Fix Array.reduce Error in JavaScript

DodaTech Updated 2026-06-24 3 min read

In this tutorial, you'll learn about How to Fix Array.reduce Error in JavaScript. We cover key concepts, practical examples, and best practices.

The Problem

Array.reduce() throws TypeError when used without an initial value on an empty array, or returns unexpected results when the reducer does not return a value.

Quick Fix

Step 1: Always provide an initial value

Calling reduce without an initial value on an empty array throws:

const empty = [];
const sum = empty.reduce((acc, val) => acc + val);
TypeError: Reduce of empty array with no initial value

Provide an initial value:

const empty = [];
const sum = empty.reduce((acc, val) => acc + val, 0);
console.log(sum);
0

Step 2: Ensure the reducer returns a value

If the reducer does not return anything, the accumulator becomes undefined:

const nums = [1, 2, 3];
const result = nums.reduce((acc, val) => {
    acc.push(val * 2);
}, []);
console.log(result);
undefined

The reducer must return the accumulator:

const nums = [1, 2, 3];
const result = nums.reduce((acc, val) => {
    acc.push(val * 2);
    return acc;
}, []);
console.log(result);
[2, 4, 6]

Step 3: Handle complex accumulator updates

For objects, spread the accumulator to preserve existing properties:

const items = [
    { category: 'fruit', name: 'apple' },
    { category: 'fruit', name: 'banana' },
    { category: 'veg', name: 'carrot' }
];
const grouped = items.reduce((acc, item) => {
    if (!acc[item.category]) {
        acc[item.category] = [];
    }
    acc[item.category].push(item.name);
    return acc;
}, {});
console.log(grouped);
{ fruit: ['apple', 'banana'], veg: ['carrot'] }

Step 4: Use reduce for type transformations

Reduce can convert arrays to other types:

const pairs = [['name', 'Alice'], ['age', '30'], ['city', 'NYC']];
const obj = pairs.reduce((acc, [key, value]) => {
    acc[key] = value;
    return acc;
}, {});
console.log(obj);
{ name: 'Alice', age: '30', city: 'NYC' }

Prevention

  • Always provide an initial value as the second argument to reduce.
  • Ensure every code path in the reducer returns the accumulator.
  • Use reduceRight when the reduction order matters (right to left).
  • Consider filter + map chaining instead of a single reduce for readability.
  • Test with empty arrays and single-element arrays.

Common Mistakes with reduce error

  1. Forgetting deriving (Show, Eq) on custom data types needed for debugging
  2. Placing the wildcard pattern first in case expressions, making all subsequent patterns unreachable
  3. Using head and tail instead of pattern matching, causing runtime errors on empty lists

These mistakes appear frequently in real-world JS code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.

Practice Exercise

Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.

This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.

FAQ

### Can I use reduce without an initial value on a non-empty array?

Yes, but it is risky. Without an initial value, reduce uses the first element as the accumulator and skips it. This works for simple sums but fails for empty arrays and makes the code less readable. Always provide an initial value for clarity and safety.

What is the difference between reduce and reduceRight?

reduce processes elements from left to right (index 0 to n-1). reduceRight processes from right to left (n-1 to 0). Use reduceRight for operations where order matters, such as reversing a sequence of operations or processing undo stacks.

When should I use reduce instead of a for loop?

Use reduce when you want a functional, immutable transformation from an array to a single value. Use a for loop when the reduction logic is complex, requires early breaking, or involves side effects. Reduce shines for simple accumulations like sums, averages, and group-by operations.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro