Course contentsShow
← JavaScript
Lesson 872 of 2,72320. Array Iteration and TransformationFree lesson

Common Reduce Pitfalls and Debugging

Learn to avoid forgetting the return statement, mutating the accumulator unintentionally, and misunderstanding the initial value.

Common Reduce Pitfalls and Debugging

You'll learn to identify and avoid the most frequent mistakes developers make when using reduce, ensuring your code works correctly every time.

The Three Most Common Reduce Mistakes

1. Forgetting the Return Statement

The most common pitfall: forgetting to return the accumulator from your callback function. Without a return, the accumulator becomes undefined on the next iteration.

// ❌ WRONG - No return!
const numbers = [1, 2, 3, 4];
const sum = numbers.reduce((acc, num) => {
  acc + num; // This doesn't return anything!
}, 0);
console.log(sum); // undefined
// ✅ CORRECT - Always return the accumulator
const sum = numbers.reduce((acc, num) => {
  return acc + num;
}, 0);
console.log(sum); // 10

2. Mutating the Accumulator Unintentionally

When your accumulator is an object or array, directly mutating it can cause unexpected side effects if that object exists elsewhere.

// ⚠️ RISKY - Mutating the accumulator
const items = ['apple', 'banana'];
const result = items.reduce((acc, item) => {
  acc.push(item.toUpperCase()); // Mutates acc
  return acc;
}, []);
// Works, but mutation can be dangerous

3. Misunderstanding the Initial Value

Forgetting the initial value causes reduce to use the first array element as the accumulator, skipping it in iteration. This breaks when your accumulator type differs from array elements.

// ❌ WRONG - No initial value for object accumulator
const nums = [1, 2, 3];
const obj = nums.reduce((acc, num) => {
  acc[num] = num * 2;
  return acc;
}); // acc starts as 1 (first element), not {}!

Key Takeaway: Always return your accumulator explicitly, be mindful of mutation when working with objects/arrays, and provide an initial value that matches your intended accumulator type—these three practices prevent 90% of reduce bugs.