Find the bug · #24 · Types and comparisons Hard JavaScript
One bad reading ruins the average
A dashboard averages sensor readings and drops bad ones, but one bad reading turns everything into NaN.
On this page
The report
A temperature dashboard averages the sensor readings and is supposed to drop the ones that fail to parse. Whenever a single sensor sends “error”, the whole average shows NaN.
The code
Read it first: what should it do? Then click the line where you think the bug is.
// Drops readings that failed to parse, then averages the rest.
function averageReading(raw) {
const readings = raw.map(Number).filter((r) => r !== NaN);
const sum = readings.reduce((a, b) => a + b, 0);
return sum / readings.length;
}Read it, then pick a line.
Try it in the console: what is NaN === NaN?
What it prints
Running it on a small example prints the output on the left. It should print the output on the right.
console.log(averageReading(['20', '22', '24']));
console.log(averageReading(['20', 'error', '24']));It prints
22 NaN
It should print
22 22
Show the answer: the bug, the fix, and how you’d find it
The bug (line 3)
Line 3 tries to drop failed readings with r !== NaN. But NaN is the one value that isn’t equal to anything, not even itself, so r !== NaN is always true and nothing is dropped. One NaN then turns the whole sum into NaN. Use Number.isNaN(r).
The fix
1// Drops readings that failed to parse, then averages the rest.2function averageReading(raw) {3 const readings = raw.map(Number).filter((r) => r !== NaN);3 const readings = raw.map(Number).filter((r) => !Number.isNaN(r));4 const sum = readings.reduce((a, b) => a + b, 0);5 return sum / readings.length;6}How you’d find it
- Reproduce: three good readings average fine; one “error” among them gives
NaN. - So the bad reading isn’t being filtered out. Print
readingsafter the filter: it still containsNaN. - Test the filter’s condition by itself:
NaN !== NaNistrue. The check can never remove anything.
The test that catches it
It fails on the code above and passes once it’s fixed. Keep it, so the bug can’t come back.
assert.equal(averageReading(['20', 'error', '24']), 22);
assert.equal(averageReading(['10']), 10);Where else this bites
- Python too:
float("nan") == float("nan")is False; usemath.isnan. indexOf(NaN)is always -1, whileincludes(NaN)finds it.