Emmanuel Akinfulubi

JavaScriptMath

Average of numbers and the empty-array case in JavaScript

Beginner · 4 min read

The average, or mean, of a list of numbers is their total divided by how many there are. The mean of 2, 4 and 9 is 15 / 3 = 5. You use it for exam marks, ratings, response times and almost any report that summarizes numbers.

The arithmetic is easy. The interesting part is the edges. What should your function return for an empty list? Why does one very large value pull the mean so far? And why do three prices that obviously add up to 54.24 come out as 54.239999999999995? In this tutorial you will write sum and mean and answer all three questions. You need to know arrays and arrow functions.

Adding up with reduce

reduce walks through an array and carries a running value along. You give it a function and a starting value:

JavaScript

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

The function receives the running total a and the next item b, and returns the new running total. The 0 at the end is where the total starts.

Here is the exercise. Try it yourself first if you like, then read on and we will build it together.

56 The mean, and the empty list

easy

Average a list of marks. Then say what your function returns for an empty list, and add three prices as floats and again as integer kobo.

Stuck? Three hints, smallest first
  1. 1. reduce with a starting value of 0 totals a list, and the total of nothing is 0.
  2. 2. The mean of an empty list is 0 / 0, and that is not 0.
  3. 3. The mean is not robust: one large value moves it a long way.

Step 1: sum and mean

Step 1

const sum = (xs) => xs.reduce((a, b) => a + b, 0);
const mean = (xs) => sum(xs) / xs.length;
const marks = [72, 88, 61, 95, 79];
console.log(sum(marks));  // 395
console.log(mean(marks)); // 79

Five marks add to 395, and 395 / 5 is 79.

Step 2: why the starting value matters

You will often see reduce written without the 0. On a normal list it works. On an empty list it doesn't:

Step 2

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

Without a starting value, reduce uses the first item, and an empty list has no first item, so it throws an error (this is node's wording; browsers may phrase it differently). With the 0, the total of nothing is 0, which is the right answer for a sum.

Step 3: the mean of nothing

Step 3

console.log(mean([])); // NaN

The total is 0 and the count is 0, and 0 / 0 is NaN, "not a number". That is mathematically fair: there is no average of nothing. But NaN causes trouble downstream. It spreads through any arithmetic it touches, and if you send it as JSON it turns into null:

JavaScript

console.log(JSON.stringify({ average: mean([]) })); // {"average":null}

So decide what an empty list should mean in your app, and return it on purpose. For example:

JavaScript

const meanOrNull = (xs) => (xs.length === 0 ? null : mean(xs));
console.log(meanOrNull([])); // null

Step 4: one big value moves it a long way

Step 4

console.log(mean([...marks, 1000])); // 232.5

Add a single mark of 1000 (a typing mistake, say) and the mean jumps from 79 to 232.5. Every value counts equally in the total, so one extreme value drags the average with it. That is why you often see the median used instead for things like incomes. The next exercise covers it.

Step 5: adding prices as decimals

Step 5

const prices = [19.99, 25.5, 8.75];
console.log(sum(prices));          // 54.239999999999995
console.log(sum(prices) === 54.24); // false

The real total is 54.24, but the computer gives 54.239999999999995. JavaScript stores numbers in binary, and most decimals, like 19.99, can't be written exactly in binary, just as 1/3 can't be written exactly as a decimal. Each price is stored a tiny bit off, and the errors add up.

Step 6: add whole kobo instead

The fix for money is to count the smallest unit, as whole numbers. In naira, that is kobo: ₦19.99 is 1999 kobo.

Step 6

const kobo = [1999, 2550, 875];
console.log(sum(kobo));       // 5424
console.log(sum(kobo) / 100); // 54.24

Whole numbers add exactly, so the total is exactly 5424 kobo. Divide by 100 once, at the end, only to display it.

Step 7: the mean inherits the sum's problem

Step 7

console.log((0.1 + 0.2 + 0.3) / 3); // 0.20000000000000004
console.log(Math.round(((0.1 + 0.2 + 0.3) / 3) * 1000) / 1000); // 0.2

A mean is a sum divided by a count, so any error in the sum carries into the mean. If you only need a few decimal places, rounding at the end, as in the second line, gives the answer you expected.

The full solution

The answer panel has sum and mean, then prints the marks total and mean, the empty-list case, the outlier, the float and kobo totals, and the mean of 0.1, 0.2 and 0.3. Press Run to see the output.

The answer

const sum = (xs) => xs.reduce((a, b) => a + b, 0);
const mean = (xs) => sum(xs) / xs.length;        // 0 / 0 when xs is empty

const marks = [72, 88, 61, 95, 79];

// The same three prices as floats, and as integer kobo.
const prices = [19.99, 25.5, 8.75];
const kobo = [1999, 2550, 875];

console.log('total          :', sum(marks));
console.log('mean           :', mean(marks));
console.log('mean of nothing:', mean([]), 'but the total of nothing is', sum([]));
console.log('with an outlier:', mean([...marks, 1000]));
console.log('float total    :', sum(prices));
console.log('kobo total     :', sum(kobo), '=', sum(kobo) / 100);
console.log('mean of tenths :', (0.1 + 0.2 + 0.3) / 3);

Output


      
8 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 8 of them and prints ok for each. That output is the proof, and the build fails if a single check fails.

8 checks

test('the five marks total 395, so the mean is 79', [sum(marks), mean(marks)], [395, 79]);
test('the mean of an empty list is NaN, because it is 0 / 0', Number.isNaN(mean([])), true);
test('though the total of an empty list is a perfectly good 0', sum([]), 0);
test('one outlier drags the mean from 79 to 232.5', mean([...marks, 1000]), 232.5);
test('adding the prices as floats misses 54.24 by a hair', [sum(prices), sum(prices) === 54.24], [54.239999999999995, false]);
test('the same money in integer kobo adds up exactly', [sum(kobo), sum(kobo) / 100], [5424, 54.24]);
test('and the mean of 0.1, 0.2 and 0.3 is not 0.2', (0.1 + 0.2 + 0.3) / 3, 0.20000000000000004);
test('rounding to three places recovers the answer you wanted', Math.round(((0.1 + 0.2 + 0.3) / 3) * 1000) / 1000, 0.2);

Two traps, both about the edges rather than the arithmetic. The empty list gives NaN, and NaN spreads: one empty group in a report of averages turns a column into null once it is serialised to JSON. Decide what an empty group means — 0, null, or "no data" — and return that deliberately.

The other is that a mean is a sum, so it inherits every problem a sum has. Money added as 19.99 + 25.5 + 8.75 lands on 54.239999999999995, which prints as the wrong figure and compares unequal to 54.24. Add kobo, divide once at the end. Note that the divide can rescue a drifted sum by accident, which is why the assertion above checks the sum rather than the average.

Common mistakes

  • Leaving out the 0 in reduce. An empty list then throws an error instead of giving a total of 0.
  • Letting NaN escape. The mean of an empty list is NaN. Decide what it should be (0, null or a message) and return that.
  • Adding money as decimals. 19.99 + 25.5 + 8.75 isn't exactly 54.24. Add whole kobo or cents, then divide once.

Try it yourself

  1. Write meanOfGroups(groups) that takes an object like { a: [1, 2], b: [] } and returns each group's mean, with null for empty groups.
  2. Find the mean of [19.99, 25.5, 8.75] by converting each price to kobo first with Math.round(price * 100).
  3. Remove the highest and lowest mark before averaging. What is the mean of the marks plus 1000 now?

Keep practising

Newsletter

New writing, when it lands.

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