liveBook · Manning

Accumulator

As explained in Secrets of the JavaScript Ninja, Third Edition

An accumulator is the intermediate value carried from one reduction step to the next and returned after the final step.

To total an array, a loop can keep a running sum. With JavaScript’s reduce method, that running value is the accumulator: the intermediate result carried from one array item to the next. section 10.1.4

Listing 10.10 Aggregating items with reduce
const numbers = [1, 2, 3, 4];
 
const sum = numbers.reduce(  #A
  (acc, number) => acc + number,  #A
  0,  #A
);  #A
 
console.assert(sum === 10, "The sum of all numbers is 10");

The initial accumulator is 0. For each number, the callback returns a new sum; after the last number, reduce returns 10. section 10.1.4

An accumulator need not be a number. It can be an object, map, buffer, or other value built from the array. A loop may be clearer for a simple sum, but understanding reduce helps when you encounter it in existing code. section 10.1.4

How Secrets of the JavaScript Ninja, Third Edition covers it

How deep it goes
Explains the initial value, callback arguments, successive returned values, and final result without exploring reduce internals.
Examples
Compares a summing loop with reduce over [1, 2, 3, 4], starting at 0 and returning 10.
What it assumes
Builds on JavaScript arrays and a summing loop while explaining the callback’s accumulator argument.
What you can do after
Evaluate/understand how a reduce callback builds a number or another kind of value from an array.
How it connects
Connects the accumulator to arrays, callbacks, reduce, and ordinary loops.

Also explained in

Compare how 7 books explain accumulator →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Secrets of the JavaScript Ninja, Third Edition. The section links point to the parts of the book it draws on.