Lesson 13 of 15

Array.reduce

Array.reduce

reduce collapses an array to a single value by applying a function repeatedly:

const numbers = [1, 2, 3, 4, 5];
const sum = numbers.reduce((acc, n) => acc + n, 0);
console.log(sum);  // 15

The callback receives two arguments:

  • acc — the accumulator, carrying the running result
  • n — the current element

The second argument (0 here) is the initial value of acc.

How it Works

acc=0,  n=1  →  acc=1
acc=1,  n=2  →  acc=3
acc=3,  n=3  →  acc=6
acc=6,  n=4  →  acc=10
acc=10, n=5  →  acc=15

Finding the Maximum

const max = [3, 1, 4, 1, 5, 9, 2, 6].reduce(
    (best, n) => n > best ? n : best,
    -Infinity
);
console.log(max);  // 9

Your Task

Write function product(numbers) that returns the product (multiplication) of all elements.

JavaScript loading...
Loading...
Click "Run" to execute your code.