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

Common Reduce Pattern: Summing Array Values

Use reduce to sum numbers in an array, the classic introduction to understanding how the accumulator evolves.

Common Reduce Pattern: Summing Array Values

What you'll learn: How to use reduce() to calculate the total sum of numbers in an array—the classic first example that makes the accumulator concept click.

The Classic Use Case

Now that you understand reduce()'s signature and the importance of initial values, let's see the most common pattern: summing numbers. This is the "hello world" of reduce() because it clearly shows how the accumulator builds up a final result.

How It Works

When summing an array like [1, 2, 3, 4], you start with an initial value of 0, then add each number to your running total:

const numbers = [1, 2, 3, 4];

const sum = numbers.reduce((accumulator, current) => {
  return accumulator + current;
}, 0);

console.log(sum); // 10

Step-by-step execution:

  • Start: accumulator = 0 (initial value)
  • First iteration: 0 + 1 = 1 (becomes new accumulator)
  • Second iteration: 1 + 2 = 3
  • Third iteration: 3 + 3 = 6
  • Fourth iteration: 6 + 4 = 10 (final result)

Even More Concise

Because we're just returning a single expression, we can make this ultra-compact:

const sum = numbers.reduce((acc, curr) => acc + curr, 0);

This is so common you'll see it everywhere in JavaScript code. The pattern is simple: accumulator holds your running total, current is the next number to add.

Why Start with 0?

If you skip the initial value on an empty array, reduce() throws an error. Starting with 0 is safe and mathematically correct for addition—it's the additive identity.

Key Takeaway: Summing array values with reduce() is the quintessential pattern—you initialize the accumulator to 0 and add each element, building up the total step by step.