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

Summing Numbers with Reduce

The classic example: using reduce to calculate the total of all numbers in an array.

Summing Numbers with Reduce

You'll learn the most common real-world use of reduce: adding up all numbers in an array.

The Classic Example

Remember how reduce processes an array down to a single value? The textbook example is calculating a sum. Instead of writing a for loop with a running total, reduce handles the accumulation pattern for you.

Here's how it works:

const prices = [10, 25, 5, 30];

const total = prices.reduce((sum, price) => {
  return sum + price;
}, 0);

console.log(total); // 70

Breaking It Down

  • Initial value: 0 (our starting total)
  • First iteration: sum is 0, price is 10 → returns 10
  • Second iteration: sum is 10, price is 25 → returns 35
  • Third iteration: sum is 35, price is 5 → returns 40
  • Fourth iteration: sum is 40, price is 30 → returns 70

Each return value becomes the next iteration's sum.

Even More Concise

Since we're just returning a single expression, arrow functions make this incredibly clean:

const total = prices.reduce((sum, price) => sum + price, 0);

One line does all the work! The reducer takes the accumulated sum and the current price, adds them together, and that result becomes the next sum.

Why This Matters

You'll see this pattern everywhere: calculating totals, finding averages (sum divided by length), or combining any numeric values. It's cleaner than manually tracking a sum variable through a loop.

Key Takeaway: Summing an array with reduce((sum, num) => sum + num, 0) is the quintessential reduce example—it adds each number to an accumulating total, starting from zero.