Boiling Down Data with reduce

Use .reduce() to collapse an array into a single value — a total, a maximum, a count, or a grouped object. The most powerful (and most feared) array method, made simple.

Step 1 of 2

reduce: many values into one

map and filter give you arrays back. reduce is different: it boils an entire array down to a single value — a total, an average, the largest item, a count, even a new object.

It walks through the array carrying a running result called the accumulator. Your function receives the accumulator so far and the current item, and returns the new accumulator:

const total = prices.reduce((sum, price) => sum + price, 0);
//                                  ^acc  ^item            ^start value

That last argument (0) is the starting value. reduce has a scary reputation, but it's just "carry a result as you walk the list." Totals in shopping carts, summing scores, counting tags — all reduce.

Think of it this way: reduce is a snowball rolling downhill. It starts small (your initial value) and each item it rolls over adds to it. At the bottom, you have one big snowball — your single final result.
Web Standard — always pass the start value

Give reduce a starting value as the second argument (0 for a sum, [] to build an array, {} for an object). It makes the behavior predictable and handles empty arrays gracefully — [].reduce((s, n) => s + n, 0) correctly returns 0.

JAVASCRIPTREAD ONLY
CONSOLE
Click "Run" to execute your code...