Why is this an issue?
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
.
Noncompliant code example
var a = double.NaN;
if (a == double.NaN) // Noncompliant; always false
{
Console.WriteLine("a is not a number"); // this is dead code
}
if (a != double.NaN) // Noncompliant; always true
{
Console.WriteLine("a is not NaN"); // this statement is not necessarily true
}
Compliant solution
if (double.IsNaN(a))
{
console.log("a is not a number");
}