Array.prototype.reduce
- Version
- es2025
- Review
- Draft
Summary#
Array.prototype.reduce combines array elements into one accumulated result. Provide an initial accumulator when you need a predictable result for an empty array.
Syntax#
array.reduce((accumulator, value, index, source) => nextValue, initialValue)
Example#
const prices = [4, 6, 8];
const total = prices.reduce((sum, price) => sum + price, 0);
console.log(total);
console.log([].reduce((sum, price) => sum + price, 0));
Expected output#
18
0
Common mistakes#
Return the accumulator from each callback. Omitting the initial value makes the first present element the accumulator and causes a TypeError if there are no elements to visit. Use map to build a parallel array from a one-to-one transformation.
Version applicability#
reduce is available from ECMAScript 5 onward. The syntax and example use ES2015 arrow functions.
Sources#
- Attribution
- DevLookup contributors
- License
- CC-BY-4.0