Calculate the average of an array in JavaScript
Beginner · 3 min read
The average, or mean, of a list is its total divided by how many items there are. It is how a teacher gets a class average, how an app shows your average daily steps, and how a shop rates a product from its reviews. The formula is simple. The interesting part is what to do when the list is empty.
In this tutorial you will write mean(xs) with reduce, see why an empty list gives NaN, learn the one reliable way to check for NaN, and write meanOrNull, which answers honestly when there is nothing to average. You need to know what an array and a function are.
Totals with reduce
reduce walks a list and builds up one value. You give it a function and a starting value. The function receives the total so far and the next item, and returns the new total:
const scores = [67, 45, 92, 58, 78];
console.log(scores.reduce((sum, n) => sum + n, 0)); // 340
console.log(scores.length); // 5
Starting from 0, it adds 67, then 45, and so on, to reach 340. Divide by the 5 scores and the average is 68.
Here is the exercise. Try it yourself first if you like, or read on and we will build it together.
57 The average of a list
easyAverage an array of test scores. Then decide what your function should do with an empty array, because the obvious implementation answers NaN.
Stuck? Three hints, smallest first
- 1. Total with a reduce, then divide by the length.
- 2. An empty array gives
0 / 0. Look up what that is. - 3.
NaNis not equal to itself, soaverage(xs) === average(xs)can be false.
Step 1: total divided by length
const scores = [67, 45, 92, 58, 78];
const mean = (xs) => xs.reduce((sum, n) => sum + n, 0) / xs.length;
console.log(mean(scores)); // 68
console.log(mean([42])); // 42
console.log(mean([-10, 10])); // 0
console.log(mean([1, 2])); // 1.5
A single value averages to itself, negatives work, and a fractional average is kept as it is, not rounded.
Step 2: try an empty list
const mean = (xs) => xs.reduce((sum, n) => sum + n, 0) / xs.length;
console.log(mean([])); // NaN
The total of nothing is 0, and the length is 0, so this is 0 / 0. In JavaScript that is NaN, short for "Not a Number". No error is thrown. NaN just appears, and if it reaches the page, it shows up as the text "NaN".
Step 3: checking for NaN
NaN is the only value in JavaScript that isn't equal to itself. So the check you would naturally write never works:
const mean = (xs) => xs.reduce((sum, n) => sum + n, 0) / xs.length;
const avg = mean([]);
console.log(avg === NaN); // false
console.log(avg === avg); // false
console.log(Number.isNaN(avg)); // true
Number.isNaN is the reliable check. It answers true only for NaN.
Step 4: answer honestly with null
An empty list has no average. Showing 0 would be a lie, because 0 is a real score. Showing "NaN" looks like a bug. Returning null says clearly "there is no answer", and the code that shows the result can then print something like "No scores yet":
const mean = (xs) => xs.reduce((sum, n) => sum + n, 0) / xs.length;
const meanOrNull = (xs) => (xs.length === 0 ? null : mean(xs));
console.log(meanOrNull([])); // null
console.log(meanOrNull([67, 45, 92, 58, 78])); // 68
condition ? a : b means "if the condition is true use a, otherwise use b". The empty list is handled before any division happens.
Step 5: decimals drift
One more thing to know. Averaging decimals doesn't always give the tidy answer you expect:
const mean = (xs) => xs.reduce((sum, n) => sum + n, 0) / xs.length;
console.log(mean([0.1, 0.2, 0.3])); // 0.20000000000000004
Computers store numbers in binary, and decimals like 0.1 can't be stored exactly, so tiny errors creep in when you add them. The fix is to round when you display the result, for example with toFixed(2), and never in the middle of a calculation.
The full solution
The answer panel has mean and meanOrNull, and prints the average of five scores, the NaN from an empty list, and the drifting decimal average. The checks use Number.isNaN, because NaN can't be compared with ===. Press Run to see the output.
const scores = [67, 45, 92, 58, 78];
const mean = (xs) => xs.reduce((sum, n) => sum + n, 0) / xs.length;
// The honest version: no average exists for an empty list, so say so.
const meanOrNull = (xs) => (xs.length === 0 ? null : mean(xs));
console.log('scores ->', scores);
console.log('mean ->', mean(scores));
console.log('empty ->', mean([]), '<- 0 / 0');
console.log('is that NaN equal to itself?', mean([]) === mean([]));
console.log('floating point bites here too:', mean([0.1, 0.2, 0.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.
test('the average of five scores', mean(scores), 68);
test('a single value averages to itself', mean([42]), 42);
test('an empty list gives NaN', Number.isNaN(mean([])), true);
test('and NaN is not equal to itself', mean([]) === mean([]), false);
test('so the honest version answers null', meanOrNull([]), null);
test('negatives average fine', mean([-10, 10]), 0);
test('a fractional average is kept whole, not rounded', mean([1, 2]), 1.5);
test('but decimals drift', mean([0.1, 0.2, 0.3]), 0.20000000000000004);
NaN is the only value in JavaScript that is not equal to itself, so if (avg === NaN) never fires and test('...', avg, NaN) passes vacuously because JSON.stringify(NaN) is "null". Number.isNaN(avg) is the only reliable check.
Returning null for an empty list is a design decision, not a nicety: NaN reaches the page as the string "NaN" and nobody can tell whether the data was missing or the maths was wrong. The last assertion is the reminder from exercise 51 — an average of decimals is not exact, so round at the point of display, never in the middle of a calculation.
Common mistakes
- Checking
avg === NaN. It is always false, even whenavgisNaN. UseNumber.isNaN(avg). - Returning 0 for an empty list. 0 is a real average, so it hides the fact that there was no data. Return
nulland let the page say so. - Rounding before averaging. Each rounding throws a little away. Average the full values, then round once for display.
Try it yourself
- Use
meanOrNullto print either "Average: 68" or "No scores yet". - Write
median(xs), the middle value after sorting. (Hint: for an even number of items, average the two in the middle.) - Average only the scores of 50 or more, using
filterfirst.