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:
sumis0,priceis10→ returns10 - Second iteration:
sumis10,priceis25→ returns35 - Third iteration:
sumis35,priceis5→ returns40 - Fourth iteration:
sumis40,priceis30→ returns70
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.