JavaScript reduce(): Accumulate with an Initial Value
Quick answer
reduce() folds present array elements into one result by passing each callback return to the next call as the accumulator.
How it works
array.reduce((acc, value, index, source) => next, initial) starts with initial. Without it, the first present element becomes the accumulator and is not passed as the value in a callback. An empty or all-hole array without an initial value throws TypeError. The accumulator may be any type.
console.log([3, 5, 8].reduce((acc, n) => acc + n, 0));Expected output in Node.js:
16The accumulator successively becomes 3, 8, then 16.
const total = [].reduce((acc, n) => acc + n, 10);console.log(total);Expected output in Node.js:
10With no present values, the explicit initial accumulator is returned.
Common mistakes
Always return the next accumulator. Pick an initial value matching the result type, such as 0 for sums.
Practice
Count the sum of quantities, using an initial zero and an empty input.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
JavaScript reduce(): Accumulate with an Initial Value — Knowledge Check
Apply the taught concept and predict the output.
Which argument follows the current value in a reduce callback?
What happens for [].reduce((a,b) => a+b) without an initial value?
If a reduce callback forgets to return, what is passed as the next accumulator?
What is the exact console output in JavaScript reduce(): Accumulate with an Initial Value example 1?
console.log([3, 5, 8].reduce((acc, n) => acc + n, 0));What is the exact console output in JavaScript reduce(): Accumulate with an Initial Value example 2?
const total = [].reduce((acc, n) => acc + n, 10);console.log(total);