NaN
is not equal to anything, even itself. Testing for equality or inequality against NaN
will yield predictable results,
but probably not the ones you want.
Instead, the best way to see whether a variable is equal to NaN
is to use Number.isNaN()
, since ES2015, or (perhaps
counter-intuitively) to compare it to itself. Since NaN !== NaN
, when a !== a
, you know it must equal NaN
.
var a = NaN; if (a === NaN) { // Noncompliant; always false console.log("a is not a number"); // this is dead code } if (a !== NaN) { // Noncompliant; always true console.log("a is not NaN"); // this statement is not necessarily true }
if (Number.isNaN(a)) { console.log("a is not a number"); } if (!Number.isNaN(a)) { console.log("a is not NaN"); }