CodeBlanks Logo Icon CodeBlanks

Reducing with reduce

JavaScript course · Beginner · Lesson 69/133

Learn to reduce an array to a single value and the accumulator idea.

Reducing with reduce

reduce shrinks the array to a single value. At each step it receives an accumulator and the current element; the callback returns the new accumulator. Whatever is left at the end is the result.

It is handy for sums, products, maximums or merging objects. You pass the starting value as the second argument; if you omit it, the first element becomes the start. Calling reduce on an empty array without a start value throws.

What is the accumulator?

The accumulator is the 'so far collected' value carried through reduce. At each step the callback combines the accumulator with the current element and produces the next accumulator.

If you give a start value, the accumulator begins as that value. If you skip it, the first element becomes the accumulator and the second becomes the current element; the first step is then skipped. Knowing this prevents bugs.

Exercise Compute the cart total

Sum all prices in the cart array into a variable total. Use 0 as the start value. Print the result.

Show example solution
const cart = [120, 80, 200];
// sum the prices
const total = cart.reduce((acc, price) => acc + price, 0);
console.log(total);

Exercise Find the largest number with reduce

Find the largest number in nums using reduce and Math.max. Store it as biggest and print it.

Show example solution
const nums = [4, 9, 2, 7];
// find the largest number
const biggest = nums.reduce((acc, n) => Math.max(acc, n));
console.log(biggest);

Test yourself

  1. What is the result of const sum = [1,2,3].reduce((acc, n) => acc + n, 0);?

    const sum = [1, 2, 3].reduce((acc, n) => acc + n, 0);
    • 6
    • 0
    • [1,2,3]
    • undefined
    Show answer

    6 — Correct. 0 + 1 + 2 + 3 = 6.

  2. compute the array's sum

    const nums = [10, 20, 30];
    const total = nums.reduce((acc, n) => ____, 0);
    console.log(total);
    Show answer
    const nums = [10, 20, 30];
    const total = nums.reduce((acc, n) => acc + n, 0);
    console.log(total);
  3. Match each reduce usage to its goal

    acc + n, 0
    sum of array
    acc * n, 1
    product of array
    Math.max(acc, n)
    largest element
    acc + n.length, 0
    total length

All lessons in Beginner