×

javascript · level 2 · unit 6 · lesson 3

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. nailed it

Tap a green word if you get lost.

meet it

folds a whole array down into one value.

.reduce() walks through an array carrying one value along, like a snowball rolling downhill and growing. That carried value is the . Your function gets the accumulator and the next item, and hands back the new accumulator.

The second argument is the starting value. prices.reduce((sum, price) => sum + price, 0) starts at 0, then adds each price. When the array runs out, the final accumulator is the answer.

Always give a starting value. It keeps empty arrays safe and makes the code easier to read.

const prices = [3, 5, 2];
const total = prices.reduce((sum, price) => sum + price, 0);
console.log(total);
const basket = [{ item: "milk", price: 1 }, { item: "bread", price: 2 }];
const bill = basket.reduce((sum, line) => sum + line.price, 0);
console.log(`Bill: £${bill}`);

It is the running total from Level 1, folded into a single line.