JS Built-ins
← Array147 / 226
ArrayArray.prototype.reducebeginner

Array.prototype.reduce() β€” sum all elements

πŸ“– Usage Example
const nums = [1, 2, 3, 4]
nums.reduce((acc, n) => acc + n, 0)  // β†’ 10

Use reduce() with an initial accumulator of 0 to compute the sum of all elements.

Array.prototype.reduce()

reduce() executes a reducer function on each element, accumulating a single result.

[1, 2, 3].reduce((acc, n) => acc + n, 0) // 6

The second argument (0) is the initial value of the accumulator.

πŸ’‘ Hints (2)
  • β€’ The reducer signature is `(accumulator, currentValue) => newAccumulator`.
  • β€’ Always provide `0` as the initial value to handle empty arrays safely.