#24 · Types and comparisons

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

Bug 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.

JavaScriptClick the line you think is wrong
// 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.

What it prints

Running it on a small example prints the output on the left. It should print the output on the right.

The example
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

  1. Reproduce: three good readings average fine; one “error” among them gives NaN.
  2. So the bad reading isn’t being filtered out. Print readings after the filter: it still contains NaN.
  3. Test the filter’s condition by itself: NaN !== NaN is true. 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; use math.isnan.
  • indexOf(NaN) is always -1, while includes(NaN) finds it.
Your progress stays on this device.