liveBook · Manning

Reduction operation

As explained in Secrets of the JavaScript Ninja, Second Edition

An Array method that applies a callback across elements to accumulate a single result.

Need one result from an array? A loop can visit every item and update a running value, but `reduce` expresses that aggregation directly. It turns an array into a single value by repeatedly applying a callback. section 9.1.4

Listing 9.12. Aggregating items with reduce
const numbers = [1, 2, 3, 4];

const sum = numbers.reduce((aggregated, number) =>             #A
                            aggregated + number, 0);           #A

assert(sum === 10, "The sum of first four numbers is 10");

The sum starts at `0`. For each number, the callback adds that number to the accumulated value; the final result is `10`. section 9.1.4

The callback receives the previous result—or the initial value on its first call—and the current item. The last callback result becomes the result of `reduce`. section 9.1.4

How Secrets of the JavaScript Ninja, Second Edition covers it

How deep it goes
Explains the initial value, callback arguments, and final result through a worked sum; leaves engine details aside.
Examples
Sums `[1, 2, 3, 4]` from an initial value of `0` to produce `10`.
What it assumes
Assumes familiarity with arrays and callbacks while explaining how the accumulated value passes between calls.
What you can do after
Apply it via `Array.reduce` to accumulate array items into one value.
How it connects
Connects reduction to arrays, callback functions, and `forEach` loops.

Also explained in

Compare how 9 books explain reduction operation →

Related concepts

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