NaN !== NaN

Well it finally happened. I finally found a use for the infamous NaN !== NaN “bug” in JavaScript. If you’ve done any JavaScript development in the last decade, you’ve almost certainly come across someone complaining or asking about NaN !== NaN. The irony is that according to the IEEE 754 specification for floating point numbers, NaN is never supposed to equal NaN.

So we’ve established that it’s not a bug, but is it ever actually useful? It seemed like one of those things you memorize without every having a need for it. I was firmly in the camp of “cool, why do I care”; until today. I found a pretty neat use for NaN !== NaN.

Suppose you are in a situation where you are comparing two numbers attached to an object. There is a chance that because of something upstream, one or both of them are undefined. You could write additional conditionals to check for it but it might end up being cleaner with a single conditional. A code example will explain it better than words.

var object1 = {};
var object2 = {};
if (parseInt(object1.value, 10) === parseInt(object2.value, 10){
console.log(object1.value.toString());
}
// Outputs nothing because the conditional evaluates to false

Without `parseInt`, the conditional would evaluate to `true` and would cause an error because you would end up calling `undefined.toString()`. By exploiting the rule that NaN != NaN, we can omit the extra ‘truthy’ check.

A single golf clap? Or a long standing ovation?

By clapping more or less, you can signal to us which stories really stand out.