reduce walks the array with an accumulator. Always pass an initial value so empty arrays and object totals behave predictably.

Source


        

Result


        

Accumulator steps

Steps appear here when you run a reduce.

Pick a reduce demo.

Important JavaScript

const scores = [10, 20, 5, 30];

const total = scores.reduce(function (acc, n) {
  return acc + n;
}, 0);
// steps: 0→10→30→35→65

const max = scores.reduce((acc, n) => (n > acc ? n : acc), scores[0]);

const players = [
  { category: "guard" },
  { category: "forward" },
  { category: "guard" }
];

const counts = players.reduce((acc, player) => {
  const key = player.category;
  acc[key] = (acc[key] || 0) + 1;
  return acc;
}, {});
// { guard: 2, forward: 1 }