Array.prototype.reduce()
The reduce()
method executes a user-supplied "reducer" callback function on each element of the array, in order, passing in the return value from the calculation on the preceding element.
The final result of running the reducer across all elements of the array is a single value.
The first time that the callback is run there is no "return value of the previous calculation". If supplied, an initial value may be used in its place. Otherwise the array element at index 0 is used as the initial value and iteration starts from the next element (index 1 instead of index 0).
Perhaps the easiest-to-understand case for reduce()
is to return the sum of all the elements in an array:
The reducer walks through the array element-by-element, at each step adding the current array value to the result from the previous step (this result is the running sum of all the previous steps) — until there are no more elements to add.
Syntax
// Arrow function
reduce((accumulator, currentValue) => { /* … */ })
reduce((accumulator, currentValue, currentIndex) => { /* … */ })
reduce((accumulator, currentValue, currentIndex, array) => { /* … */ })
reduce((accumulator, currentValue) => { /* … */ }, initialValue)
reduce((accumulator, currentValue, currentIndex) => { /* … */ }, initialValue)
reduce((accumulator, currentValue, currentIndex, array) => { /* … */ }, initialValue)
// Callback function
reduce(callbackFn)
reduce(callbackFn, initialValue)
// Inline callback function
reduce(function (accumulator, currentValue) { /* … */ })
reduce(function (accumulator, currentValue, currentIndex) { /* … */ })
reduce(function (accumulator, currentValue, currentIndex, array) { /* … */ })
reduce(function (accumulator, currentValue) { /* … */ }, initialValue)
reduce(function (accumulator, currentValue, currentIndex) { /* … */ }, initialValue)
reduce(function (accumulator, currentValue, currentIndex, array) { /* … */ }, initialValue)
Parameters
callbackFn
: A function to execute for each element in the array. Its return value becomes the value of the
accumulator
parameter on the next invocation ofcallbackFn
. For the last invocation, the return value becomes the return value ofreduce()
.The function is called with the following arguments:
accumulator
- : The value resulting from the previous call to
callbackFn
. On first call,initialValue
if specified, otherwise the value ofarray[0]
.
- : The value resulting from the previous call to
currentValue
- : The value of the current element. On first call, the value of
array[0]
if aninitialValue
was specified, otherwise the value ofarray[1]
.
- : The value of the current element. On first call, the value of
currentIndex
- : The index position of
currentValue
in the array. On first call,0
ifinitialValue
was specified, otherwise1
.
- : The index position of
array
- : The array
reduce()
was called upon.
- : The array
initialValue
optional- : A value to which
accumulator
is initialized the first time the callback is called. IfinitialValue
is specified,callbackFn
starts executing with the first value in the array ascurrentValue
. IfinitialValue
is not specified,accumulator
is initialized to the first value in the array, andcallbackFn
starts executing with the second value in the array ascurrentValue
. In this case, if the array is empty (so that there's no first value to return asaccumulator
), an error is thrown.
- : A value to which
Return value
The value that results from running the "reducer" callback function to completion over the entire array.
Exceptions
- : The array contains no elements and
initialValue
is not provided.
- : The array contains no elements and
Description
The reduce()
method is an iterative method. It runs a "reducer" callback function over all elements in the array, in ascending-index order, and accumulates them into a single value. Every time, the return value of callbackFn
is passed into callbackFn
again on next invocation as accumulator
. The final value of accumulator
(which is the value returned from callbackFn
on the final iteration of the array) becomes the return value of reduce()
.
callbackFn
is invoked only for array indexes which have assigned values. It is not invoked for empty slots in sparse arrays.
Unlike other iterative methods, reduce()
does not accept a thisArg
argument. callbackFn
is always called with undefined
as this
, which gets substituted with globalThis
if callbackFn
is non-strict.
reduce()
is a central concept in functional programming, where it's not possible to mutate any value, so in order to accumulate all values in an array, one must return a new accumulator value on every iteration. This convention propagates to JavaScript's reduce()
: you should use spreading or other copying methods where possible to create new arrays and objects as the accumulator, rather than mutating the existing one. If you decided to mutate the accumulator instead of copying it, remember to still return the modified object in the callback, or the next iteration will receive undefined.
reduce()
does not mutate the array on which it is called, but the function provided as callbackFn
can. Note, however, that the length of the array is saved before the first invocation of callbackFn
. Therefore:
callbackFn
will not visit any elements added beyond the array's initial length when the call toreduce()
began.- Changes to already-visited indexes do not cause
callbackFn
to be invoked on them again. - If an existing, yet-unvisited element of the array is changed by
callbackFn
, its value passed to thecallbackFn
will be the value at the time that element gets visited. Deleted elements are not visited.
The reduce()
method is generic. It only expects the this
value to have a length
property and integer-keyed properties.
When to not use reduce()
Recursive functions like reduce()
can be powerful but sometimes difficult to understand, especially for less-experienced JavaScript developers. If code becomes clearer when using other array methods, developers must weigh the readability tradeoff against the other benefits of using reduce()
. In cases where reduce()
is the best choice, documentation and semantic variable naming can help mitigate readability drawbacks.
Edge cases
If the array only has one element (regardless of position) and no initialValue
is provided, or if initialValue
is provided but the array is empty, the solo value will be returned without calling callbackFn
.
If initialValue
is provided and the array is not empty, then the reduce method will always invoke the callback function starting at index 0.
If initialValue
is not provided then the reduce method will act differently for arrays with length larger than 1, equal to 1 and 0, as shown in the following example:
const getMax = (a, b) => Math.max(a, b);
// callback is invoked for each element in the array starting at index 0
[1, 100].reduce(getMax, 50); // 100
[50].reduce(getMax, 10); // 50
// callback is invoked once for element at index 1
[1, 100].reduce(getMax); // 100
// callback is not invoked
[50].reduce(getMax); // 50
[].reduce(getMax, 1); // 1
[].reduce(getMax); // TypeError