Comparing NaN and -0 With Object.is()

The old website page now labels the rain and the heaters correctly. Back in the readings check, the next line to port marks a temperature that hasn’t changed since the station’s last reading. In the 09:00 batch, that’s mill at 7.4°C twice, and orchard, whose failed thermometer sent nan both times.

That second case is why the Python script needs a helper at all. In this lesson, you’ll meet the built-in JavaScript method that does the helper’s job and the one value where it disagrees with === in a way you can see on the website.

Count Two Failed Readings as Unchanged

In Python, nan == nan is False, so a plain == would call orchard’s two failed readings different. The check’s same_temp() helper adds the missing case by hand:

Language: Python
import math

def same_temp(a, b):
    return a == b or (math.isnan(a) and math.isnan(b))

JavaScript’s NaN follows the same floating-point rule, so NaN === NaN is false, exactly as in Python. As with == math.nan in Python, comparing a temperature with === NaN never returns true, so Number.isNaN() is how you find a lone NaN.

You could port the helper line for line with Number.isNaN(), but JavaScript already has it built in, for every pair except a -0 and a 0, which the next section covers. The static method Object.is(a, b) asks whether two values are the same value, and it counts NaN as the same as itself. In the check, it takes the helper’s place:

Language: JavaScript
const reading = { station: "orchard", seq: 2290, temp: NaN, lastTemp: NaN };

// Python: unchanged = same_temp(reading["temp"], reading["last_temp"])
const unchanged = Object.is(reading.temp, reading.lastTemp);
console.log(reading.temp === reading.lastTemp, unchanged);

Locked learning resources

Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Already a member? Sign-In

Locked learning resources

The full lesson is for members only. Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Already a member? Sign-In

Become a Member to join the conversation.