Sum and multiply an array with reduce in JavaScript
Beginner · 4 min read
Adding up a list is one of the first things anyone needs: the total of a shopping cart, the sum of a column, the number of points in a game. JavaScript's tool for squashing a whole list into one value is reduce. It is also the array method beginners find hardest to read, so this lesson takes it slowly.
In this tutorial you will add up an array and multiply one out with reduce. Then you will break it on purpose, calling it on an empty array without a starting value, and read the error. You should know arrays and arrow functions.
What reduce does
reduce walks through the array and carries one value along with it, called the accumulator. At each item, your function gets the accumulator so far and the current item, and returns the new accumulator. When the walk ends, the last accumulator is the answer.
Here is a loop that does the same thing, so you can see the shape:
let total = 0; // the starting value
for (const n of [1, 2, 3]) {
total = total + n; // the new accumulator
}
console.log(total); // 6
reduce packs those three pieces, the starting value, the step and the result, into one call: xs.reduce((total, n) => total + n, 0). The function comes first and the starting value, also called the initial value, comes second.
Here is the exercise. Try it yourself first if you like, or read on and we will build it step by step.
30 reduce: a sum and a product
easyAdd up an array and multiply it out with reduce. Then call reduce on an empty array with no initial value and read the error.
Stuck? Three hints, smallest first
- 1. The callback takes the accumulator first, then the element:
(total, n) => total + n. - 2. The initial value is the second argument to
reduce, and it decides the type of the result. - 3. With no initial value, the first element becomes the accumulator — and an empty array has no first element.
Step 1: a sum
const sum = (xs) => xs.reduce((total, n) => total + n, 0);
console.log(sum([1, 2, 3, 4])); // 10
Trace it by hand. total starts at 0. Then 0 + 1 is 1, 1 + 2 is 3, 3 + 3 is 6, 6 + 4 is 10. The accumulator always comes first in the callback, the item second.
Step 2: a product
To multiply, change + to * and change the starting value to 1.
const product = (xs) => xs.reduce((total, n) => total * n, 1);
console.log(product([2, 3, 4])); // 24
console.log([2, 3, 4].reduce((t, n) => t * n, 0)); // 0
Why 1? Because multiplying by 1 changes nothing, just as adding 0 changes nothing. The second line shows the wrong turn: start a product at 0 and every step multiplies by zero, so the answer is always 0. At least that mistake shows up straight away.
Step 3: the empty array
What does sum([]) give?
const sum = (xs) => xs.reduce((total, n) => total + n, 0);
console.log(sum([])); // 0
There are no items, so the callback never runs, and reduce returns the starting value. A total of nothing is 0. That is the right answer.
Step 4: leave out the starting value
The starting value is optional. Without it, reduce uses the first item as the accumulator and starts walking from the second item. For a sum of numbers that gives the same answer. Now try it on an empty array:
try {
[].reduce((a, b) => a + b);
} catch (e) {
console.log(e.constructor.name); // TypeError
console.log(e.message); // Reduce of empty array with no initial value
}
There is no first item to start with, so reduce throws a TypeError. The message is node's wording; browsers may phrase it differently. This crash tends to happen in real use, not in testing: a list that was filtered down to nothing, or a cart with no items yet.
Step 5: one item, no starting value
There is one more odd case.
let calls = 0;
const lone = [5].reduce((a, b) => { calls++; return a + b; });
console.log(lone); // 5
console.log(calls); // 0
With one item and no starting value, the item becomes the accumulator and there is nothing left to walk over. The callback never runs at all, and you get the item back as it is.
Step 6: the starting value sets the type
The starting value also decides what kind of answer you get.
console.log(['a', 'b'].reduce((acc, c) => acc + c, '')); // ab
console.log([0.1, 0.2].reduce((t, n) => t + n, 0)); // 0.30000000000000004
Starting with an empty string builds a string. The second line is not a reduce bug: computers store decimals like 0.1 slightly inexactly, so adding them can be off by a tiny amount. For money, work in whole cents (or kobo) instead.
The full solution
The panel defines sum and product, then runs every case above, including the empty array with no starting value. Press Run and read the error name it prints.
const sum = (xs) => xs.reduce((total, n) => total + n, 0);
const product = (xs) => xs.reduce((total, n) => total * n, 1);
const emptyNoSeed = (() => {
try { return [].reduce((a, b) => a + b); } catch (e) { return e.constructor.name; }
})();
// With one element and no initial value, the callback never runs at all.
let calls = 0;
const lone = [5].reduce((a, b) => { calls++; return a + b; });
console.log('sum([1,2,3,4]) :', sum([1, 2, 3, 4]));
console.log('product([2,3,4]) :', product([2, 3, 4]));
console.log('sum([]) :', sum([]), '<- the initial value');
console.log('[].reduce with no initial value:', emptyNoSeed);
console.log('[5].reduce with no initial value:', lone, 'after', calls, 'calls');
console.log('a wrong seed shows up at once: product with 0 ->', [2, 3, 4].reduce((t, n) => t * n, 0));
console.log('floats do not add up exactly:', [0.1, 0.2].reduce((t, n) => t + n, 0));
Output
9 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 9 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('a sum', sum([1, 2, 3, 4]), 10);
test('a product', product([2, 3, 4]), 24);
test('an empty array returns the initial value', sum([]), 0);
test('with no initial value, an empty array throws', emptyNoSeed, 'TypeError');
test('with one element and no initial value the callback never runs', calls, 0);
test('and that element is returned as it is', lone, 5);
test('the seed decides the type of the result', ['a', 'b'].reduce((acc, c) => acc + c, ''), 'ab');
test('a seed of 0 ruins a product', [2, 3, 4].reduce((t, n) => t * n, 0), 0);
test('and floating point still does not add up', [0.1, 0.2].reduce((t, n) => t + n, 0), 0.30000000000000004);
Also Basic 22, which sums with a loop. The angle here is reduce's second argument, because that is where the bugs are. Omit it and the first element becomes the accumulator, which works for a sum of numbers, produces nonsense for a sum of strings, and throws TypeError on an empty array — the one case your tests are least likely to cover.
Always pass an initial value. It documents the result type, it makes the empty case correct instead of fatal, and it is the difference between a total of 0 and a crash on a filtered-to-nothing list.
Common mistakes
- Leaving out the starting value. It crashes on an empty array. Always pass one:
0for a sum,1for a product. - Putting the arguments in the wrong order. The callback is
(accumulator, item), accumulator first. - Forgetting to return. With curly braces around the callback body, you must write
return, or the next step getsundefined.
Try it yourself
- Use
reduceto find the total price of[{ price: 450 }, { price: 900 }, { price: 300 }]. - Count how many numbers in
[3, 8, 1, 9, 4]are bigger than 3, usingreduceand a starting value of0. - Work out the average of
[2, 4, 9]withsum. What should the average of[]be?