JavaScript Array.prototype.reduce() Method
The reduce() method combines all elements of an array into a single value, such as a total, by calling a function that carries a running result from one element to the next.
Description
The reduce() method runs a reducer function on each element, passing along the result of the previous call, called the accumulator. The final accumulator is returned. It can produce any kind of value: a sum, an object that groups items, a new array, or a single maximum.
Always give an initialValue. Without one, an empty array throws a TypeError, and the type of the result depends on the first element. For simple tasks, a clearer method often exists: Math.max(...arr), Object.groupBy() or a for...of loop can be easier to read than a complex reducer.
The callback also receives the index and the array as its third and fourth arguments. Returning a new object or array on every step, as in (acc, x) => ({ ...acc, [x.id]: x }), copies the accumulator each time and becomes slow for large arrays; mutating the accumulator and returning it is much faster and safe, because the accumulator is your own object.
Syntax
array.reduce(callbackFn)
array.reduce(callbackFn, initialValue)Parameters
- callbackFnA function that combines the running result with each element. It receives
accumulator,currentValue,indexandarray, and returns the new accumulator. - initialValueOptional, but recommended. The starting value of the accumulator. Without it, the first element is used and the loop starts at the second.
Return Value
The final value of the accumulator.
Exceptions
- TypeErrorThrown if the array is empty and no
initialValueis given.
Example
Browser Support
The following information will show you the current browser support for the Array.prototype.reduce() method. Hover over a browser icon to see the version that first introduced support for this method.
Desktop





Tablets & Mobile





