CodeBlanks Logo Icon CodeBlanks

reduce

Learn to reduce an array to a single value with .reduce.

The reduce method

The reduce method folds an array into a single value. It is used for sums, products, averages or joining items. The result is one value, not an array.

The syntax is array.reduce(fn, initial). Here fn takes two parameters: (accumulator, element). The accumulator carries the running result, element is the current item, and initial is the accumulator's starting value.

Example: [1, 2, 3].reduce((sum, n) => sum + n, 0) returns 6. Steps: 0+1=1, 1+2=3, 3+3=6.

How to call reduce

The second parameter of reduce — the initial value — matters. With an empty array and no initial value, reduce throws. For sums, averages and similar tasks it is safe to always pass it explicitly.

Common initial values are 0 for sums, 1 for products, and '' (empty string) for joining. For example ['a', 'b', 'c'].reduce((acc, l) => acc + l, '') returns 'abc'.

The accumulator is updated each step, and its final value is what reduce returns. So the function's return value must be the value to carry into the next step.

Practice Cart total

Define an array of prices [120, 45, 200]. Use reduce with initial value 0 to compute the sum of all prices, and print the result with console.log.

Starter code

index.js
const prices = [120, 45, 200];
// Compute the total with reduce and print

Sample solution

index.js
const prices = [120, 45, 200];
const total = prices.reduce((sum, p) => sum + p, 0);
console.log(total);

Expected output

365

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Match the reduce parts

Term Meaning
accumulator Running result
element Current array item
initial Starting value of accumulator
single value What reduce returns

2 Why does the initial value matter?

  • Empty arrays do not throw Correct answer
  • For syntax
  • For performance
  • The type changes

Explanation: the initial value prevents reduce from throwing on an empty array.

3 Compute the sum

Question
const nums = [1, 2, 3];
const total = nums.reduce((sum, n) => sum ____ n, 0);
Answer
const nums = [1, 2, 3];
const total = nums.reduce((sum, n) => sum + n, 0);

Explanation: sum + n adds each element to the accumulator.

All lessons in Beginner