The Initial Value: When to Provide It and Why
You'll learn when and why to include the optional initial value in reduce(), and what happens when you skip it.
When calling reduce(), you can provide an initial value as the second argument after the callback. This starting value becomes the accumulator's first value. If you omit it, reduce() uses the array's first element as the initial accumulator and starts processing from the second element.
When to Always Provide an Initial Value
For empty arrays: If your array might be empty and you don't provide an initial value, reduce() throws a TypeError. Providing an initial value (like 0 for sums or [] for arrays) makes your code safer.
const empty = [];
// empty.reduce((sum, num) => sum + num); // TypeError!
const safe = empty.reduce((sum, num) => sum + num, 0); // Returns 0
When returning a different type: If you're transforming an array of numbers into an object, or strings into an array, the initial value sets the correct type:
const nums = [1, 2, 3];
const obj = nums.reduce((acc, num) => {
acc[num] = num * 2;
return acc;
}, {}); // Must start with {}
// Result: {1: 2, 2: 4, 3: 6}
When You Can Omit It
For simple operations on non-empty arrays of the same type (like summing numbers), omitting the initial value works fine—but providing it is still safer and more explicit.
Key Takeaway: Always provide an initial value to reduce() unless you're certain the array is non-empty and the first element is a valid starting accumulator. It prevents errors and makes your intent crystal clear.