The Initial Value Argument
You'll learn: Why the second argument to reduce determines where your accumulation starts and what happens if you leave it out.
Starting Point Matters
When you call reduce, the initial value is the second argument. It sets the very first value of the accumulator before any array elements are processed.
Think of it like starting a piggy bank: if you begin with 10. If you start with an empty piggy bank (no initial value), your first coin becomes the starting amount.
How It Works
const numbers = [1, 2, 3, 4];
// With initial value of 0
const sum = numbers.reduce((acc, num) => acc + num, 0);
// First call: acc = 0, num = 1 → returns 1
// Second call: acc = 1, num = 2 → returns 3
// Result: 10
// With initial value of 100
const sumPlus100 = numbers.reduce((acc, num) => acc + num, 100);
// First call: acc = 100, num = 1 → returns 101
// Result: 110
Without an initial value, reduce uses the first array element as the accumulator and starts processing from the second element:
const sum = numbers.reduce((acc, num) => acc + num);
// First call: acc = 1 (first element), num = 2
// Skips the first element as a processing step
// Result: 10 (same, but fewer iterations)
When It's Critical
The initial value becomes essential when building objects or arrays, or when your array might be empty:
// Building an object – MUST have initial value
const counts = ['a', 'b', 'a'].reduce((acc, letter) => {
acc[letter] = (acc[letter] || 0) + 1;
return acc;
}, {}); // {} is the initial value
Key Takeaway: The initial value sets your accumulator's starting point; always provide it when working with empty arrays or building non-primitive values like objects.