How to Fix Array.reduce Error in JavaScript
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
reduceRightwhen the reduction order matters (right to left). - Consider
filter+mapchaining instead of a single reduce for readability. - Test with empty arrays and single-element arrays.
Common Mistakes with reduce error
- Forgetting
deriving (Show, Eq)on custom data types needed for debugging - Placing the wildcard pattern first in case expressions, making all subsequent patterns unreachable
- Using
headandtailinstead 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
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro