.reduce() (JavaScript)

.reduce() boils an array down to a single value by running a function that accumulates a result as it walks through each element.

JavaScript

You provide a reducer function and a starting value. On each step the function receives the running total (the accumulator) and the current element, and returns the new total.

It is commonly used to sum numbers, build objects, or flatten arrays.

Syntax

array.reduce((accumulator, element) => ..., initialValue)

Examples

JavaScript

const nums = [1, 2, 3, 4];
const sum = nums.reduce((total, n) => total + n, 0);
console.log(sum);

Output:

10

Learn it in a lesson

See also

Back to the Dictionary