In JavaScript, NaN
stands for "Not-a-Number." It is a special value representing a numeric data type that is not a valid number.
NaN
is returned as a result when an arithmetic operation or mathematical function is performed, and the result is undefined or
unrepresentable as a valid number.
Comparing a value with NaN
in JavaScript can be problematic because of the way NaN
behaves in comparison operations. The
reason is that NaN
is not equal to any value, including itself, and this behavior can lead to unexpected results.
const 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
}
To check if a value is NaN
, you should use the isNaN()
function:
const a = NaN;
if (isNaN(a)) {
console.log("a is not a number");
}
if (!isNaN(a)) {
console.log("a is not NaN");
}
Keep in mind that isNaN()
can be a bit quirky since it tries to convert its argument into a number before checking if it is
NaN
. If the argument cannot be converted into a number, isNaN()
will return true, which may not be the desired behavior in
all cases.
Instead, you should prefer using the Number.isNaN()
method over isNaN()
to perform a strict check for NaN
without any type conversion:
const a = NaN;
if (Number.isNaN(a)) {
console.log("a is not a number");
}
if (!Number.isNaN(a)) {
console.log("a is not NaN");
}