Course contentsShow
← JavaScript
Lesson 456 of 2,72312. Higher-Order FunctionsFree lesson

Reducing Without an Initial Value

When reduce uses the first element as initial accumulator and starts at index 1, plus the empty array edge case.

Reducing Without an Initial Value

You'll learn what happens when you call reduce() without providing an initial value.

The Core Idea

When you omit the second argument to reduce(), JavaScript doesn't start with a separate initial value. Instead, it uses the first element of the array as the initial accumulator and begins iterating from the second element (index 1).

Think of it like organizing a line of people to pass a message. If you don't give them a starting message, the first person simply shares their own information, and the second person becomes the first to actually combine messages.

How It Works

const numbers = [10, 20, 30];

const sum = numbers.reduce((acc, curr) => {
  return acc + curr;
});
// First call: acc = 10 (first element), curr = 20 (second element)
// Second call: acc = 30, curr = 30
// Result: 60

Without an initial value, reduce() makes one fewer callback invocations because it skips the first element.

The Empty Array Edge Case

Here's the gotcha: if your array is empty and you provide no initial value, reduce() throws a TypeError:

const empty = [];
// empty.reduce((acc, curr) => acc + curr); // TypeError!

If the array has only one element and no initial value, reduce() returns that single element without ever calling the reducer function:

const single = [42];
const result = single.reduce((acc, curr) => acc + curr);
// result is 42, reducer never called

Key Takeaway: Omitting the initial value makes reduce() use the first array element as the starting accumulator, but always provide an initial value when working with potentially empty arrays to avoid runtime errors.