Example 1 — Sum All Numbers
Start at 0 and add each element to the accumulator.
const numbers = [1, 2, 3, 4, 5];
const sum = numbers.reduce((acc, num) => {
return acc + num;
}, 0);
console.log(sum);
// 15 How It Works
- Set
initialValueto0. Sums should not start from the first element alone. - Add each number.
acc + numbecomes the next accumulator. - Walk left to right. 0→1→3→6→10→15.
- Return the total.
sumis15.

