liveBook · Manning

Reduction operation

As explained in Essential TypeScript 5, Third Edition

The reduce method applies a function across an array's elements to produce a single accumulated result.

An array reduction applies a callback to successive values to produce one result. Use `reduce` when a function receives any number of values but must return one total. A rest parameter collects the arguments into an array; `reduce` then accumulates them. section 3.3.3

Sum a variable number of prices

In `primer/index.js`: ```js function sumPrices(...numbers) { return numbers.reduce((total, val) => total + val, 0); } console.log(sumPrices(100, 200, 300)); // 600 console.log(sumPrices(100, "100")); // "100100" ``` The callback receives the accumulated total and the next value; `0` supplies the starting total. The second call concatenates because the addition operator encounters a string. Changing the number of arguments does not fix that type problem. section 3.3.3

Convert values before adding them

To keep the total numeric, convert each value and substitute zero when conversion produces `NaN`: ```js function sumPrices(...numbers) { return numbers.reduce((total, val) => total + (Number.isNaN(Number(val)) ? 0 : Number(val)), 0); } console.log(sumPrices(100, "100")); // 200 console.log(sumPrices(100, 200, undefined, false, "hello")); // 300 ``` Here `false` converts to zero; `undefined` and `"hello"` produce `NaN` and contribute zero. The arrow function is a shorter way to write the callback. section 3.3.3

An array’s `reduce` method is distinct from a Redux reducer. A Redux reducer is a function used to modify data-store state, not a call that folds array elements into one value. section 3.3.3 section 20.5

How Essential TypeScript 5, Third Edition covers it

How deep it goes
Works through callbacks, an initial value, string concatenation, numeric conversion, and `NaN` handling without exploring reduce internals.
Examples
Shows a price-summing function that first concatenates a string price, then converts values and substitutes zero for `NaN`.
What it assumes
Assumes basic JavaScript function syntax while explaining rest parameters and introducing arrow functions as callbacks.
What you can do after
Build it from scratch as a variable-argument sum that handles string prices and values that convert to `NaN`.
How it connects
Connects `reduce` to rest parameters, arrow functions, numeric conversion, and `NaN` checks; distinguishes it from Redux reducers.

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 Essential TypeScript 5, Third Edition. The section links point to the parts of the book it draws on.