JavaScript (ES2026) reference · Array Methods
JavaScript Array reduce() Method
Reduce the array to a single value by running a reducer function on each element, carrying an accumulator along.
JavaScript (ES2026) Since ES5
Syntax
array.reduce(callbackFn, initialValue)
Parameters
| Parameter | Description |
|---|---|
callbackFn |
Called with (accumulator, element, index, array); its return value becomes the next accumulator. |
initialValue optional |
The starting accumulator. Strongly recommended. |
Return value
The final accumulator value.
Examples
const nums = [1, 2, 3, 4];
console.log(nums.reduce((sum, n) => sum + n, 0));
Output
10
const words = ["apple", "avocado", "banana"];
const byLetter = words.reduce((acc, w) => {
(acc[w[0]] ??= []).push(w);
return acc;
}, {});
console.log(byLetter);
Output
{ a: [ 'apple', 'avocado' ], b: [ 'banana' ] }try {
[].reduce((a, b) => a + b);
} catch (e) {
console.log(e.name);
}
console.log([].reduce((a, b) => a + b, 0));
Output
TypeError 0
Good to know
Without an initialValue, reduce() uses the first element and throws TypeError on an empty array. For
grouping, Object.groupBy() (ES2024) is often clearer than reduce().
Version history
| Version | Change |
|---|---|
| JavaScript ES5 | Added |
Related
array.reduceRight()· Like reduce(), but processes the array from the last element to the first.array.map()· Return a new array with the results of calling a function on every element. The original array is unchanged.array.filter()· Return a new array with only the elements that pass a test function. The original array is not changed.- JavaScript Arrays · tutorial
- JavaScript Array Methods · tutorial