Emmanuel Akinfulubi

JavaScriptBasic

Find the sum and product of an array in JavaScript

Beginner · 4 min read

Adding up a list of numbers is one of the first things you do with arrays: a shopping cart total, the score across several rounds, the steps you walked this week. Multiplying a list together is less common, but it uses exactly the same tool. In this tutorial you will write two tiny functions, sum and product. Each takes an array of numbers and gives back one number.

Along the way you will answer a question that sounds like a trick: what is the sum of an empty list, and what is its product? The answers are 0 and 1. By the end you will see why those are the only sensible choices.

You need to know what an array and an arrow function are. The reduce method is explained from the start.

What reduce does

reduce walks through an array and boils it down to a single value. You give it two things: a function that combines the result so far with the next item, and a starting value.

JavaScript

const total = [1, 2, 3].reduce((total, n) => total + n, 0);
console.log(total); // 6

Read it like this. The running total starts at 0. Then reduce visits each item in turn: 0 + 1 is 1, 1 + 2 is 3, 3 + 3 is 6. When the array runs out, reduce returns the running total.

That running result is often called the accumulator. It is just a value reduce carries for you from one step to the next.

Pick a starting value that changes nothing

The starting value should be a number that has no effect on the result. For adding, that number is 0. For multiplying, it is 1. Mathematicians call this the identity of the operation.

JavaScript

console.log(5 + 0); // 5: adding 0 changes nothing
console.log(5 * 1); // 5: multiplying by 1 changes nothing
console.log(5 * 0); // 0: multiplying by 0 changes everything

Keep that last line in mind. It is the wrong turn waiting in Step 2.

Here is the exercise. Try it on your own first if you like, or read on and we will build it together.

22 Sum and product of an array

easy

Given a list of numbers, produce their sum and their product. Decide what each should be for an empty list and justify it.

Stuck? Three hints, smallest first
  1. 1. reduce takes a starting value. For a sum that is 0; for a product it is 1.
  2. 2. Those starting values are the identity for each operation: adding 0 or multiplying by 1 changes nothing.
  3. 3. Leave the starting value out and reduce throws on an empty array. Try it.

Step 1: the sum

Start the running total at 0 and add each number to it.

Step 1

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

A list with one number sums to that number, because 0 + 7 is 7.

Step 2: the product

The obvious move is to copy sum and change + to *. If you copy the starting value too, this happens:

JavaScript

const badProduct = (values) => values.reduce((total, n) => total * n, 0);
console.log(badProduct([1, 2, 3, 4, 5])); // 0

The running result starts at 0, and 0 times anything is 0. Every product comes out as zero. The fix is to start at 1, the value that changes nothing when you multiply:

Step 2

const product = (values) => values.reduce((total, n) => total * n, 1);
console.log(product([1, 2, 3, 4, 5])); // 120
console.log(product([1, 2, 0, 4]));    // 0

Now 1 * 1 * 2 * 3 * 4 * 5 is 120. A real zero inside the list still makes the product zero, which is correct.

Step 3: the empty list

What should sum([]) and product([]) return? With nothing to visit, reduce simply hands back the starting value:

JavaScript

console.log(sum([]));     // 0
console.log(product([])); // 1

An empty product being 1 looks odd at first. Think of it this way: product([2, 3]) should equal 1 * 2 * 3. Take away the 2 and the 3, and what is left is the 1. Any other answer would break that pattern.

Step 4: always pass the starting value

reduce lets you leave the starting value out. It then uses the first item as the start. That seems to work:

JavaScript

console.log([1, 2, 3].reduce((a, b) => a + b)); // 6

But on an empty array there is no first item, so it throws an error:

JavaScript

try {
  [].reduce((a, b) => a + b);
} catch (err) {
  console.log(err.constructor.name); // TypeError
  console.log(err.message);          // Reduce of empty array with no initial value
}

try runs the code inside it, and catch receives the error if one is thrown, so the program keeps going. This bug is easy to miss, because it only appears on the day your list happens to be empty: an empty cart, a user with no scores yet. Passing 0 or 1 costs two characters and removes the crash.

The full solution

The complete answer has both functions, tries them on a normal list and an empty one, and shows the error you get without a starting value. Press Run to see the output.

The answer

// The starting value is the identity: 0 for addition, 1 for multiplication.
const sum = (values) => values.reduce((total, n) => total + n, 0);
const product = (values) => values.reduce((total, n) => total * n, 1);

const nums = [1, 2, 3, 4, 5];

console.log('sum    :', sum(nums));
console.log('product:', product(nums));
console.log('empty sum    :', sum([]));
console.log('empty product:', product([]));

// Without a starting value, reduce throws on an empty array:
let threw = false;
try {
  [].reduce((a, b) => a + b);
} catch (err) {
  threw = true;
  console.log('no starting value on []:', err.constructor.name);
}

Output


      
7 checks that prove this answer

You do not have to read these. They are part of the answer panel above, so pressing Run there executes all 7 of them and prints ok for each. That output is the proof, and the build fails if a single check fails.

7 checks

test('sum of 1..5', sum(nums), 15);
test('product of 1..5', product(nums), 120);
test('empty sum is 0', sum([]), 0);
test('empty product is 1', product([]), 1);
test('a single value', sum([7]), 7);
test('a zero in the list makes the product zero', product([1, 2, 0, 4]), 0);
test('reduce with no starting value throws on empty', threw, true);

An empty product being 1 looks odd and is right. The starting value has to be the identity for the operation, the value that changes nothing, so that product([2, 3]) equals 1 * 2 * 3. Use 0 there and every product would be zero. And always pass the starting value: without it, reduce throws on an empty array, which is a crash waiting for the day your list happens to be empty.

Common mistakes

  • Starting a product at 0. Every result becomes 0. Multiplication starts at 1.
  • Leaving out the starting value. It works until the array is empty, then throws a TypeError.
  • Mixing up the two arguments. In (total, n) => total + n, the first argument is the running result and the second is the current item. Swap their meaning and longer functions get confusing fast.

Try it yourself

  1. Write average(values) using your sum. Decide what it should return for an empty list, since dividing by 0 gives NaN.
  2. Use reduce to find the largest number in [4, 9, 2]. What is a good starting value? (Hint: try -Infinity.)
  3. Add up the price of every item in [{ price: 500 }, { price: 1200 }]. Only the combining function needs to change.

Keep practising

Newsletter

New writing, when it lands.

Occasional notes on shipping software with AI agents. No schedule, no filler, unsubscribe in one click.