JavaScript

Sum values with reduce and an initial value

Supply an initial accumulator when using reduce to sum values. An initial zero makes the empty-array result well defined and keeps the accumulator type predictable.

Worked example

Node.js example · save as example.mjs and run node example.mjs

const prices = [12, 8, 5];
const total = prices.reduce((sum, price) => sum + price, 0);
const empty = [].reduce((sum, price) => sum + price, 0);
console.log(total, empty);

How it works

Each callback receives the running sum and the next price. Starting at zero gives 12, then 20, then 25. An empty array never calls the callback and simply returns the initial value. This avoids the error caused by reducing an empty array without one.

Limits and mistakes

The plus operator concatenates strings, so a string price can turn a numeric total into text. Validate input types first. Binary floating-point rounding also means ordinary decimal addition is not exact financial arithmetic.

Check the result

Expect 25 and 0. Include an empty list and a string price in your tests; the latter should be rejected or converted deliberately before summing.

Sources

Reference documentation for the behavior used in this guide: