# use-isnan

Disallow incorrect comparisons against NaN.

NaN is a special Number value used to represent "not a number" results in calculations. This value is specified in the IEEE Standard for Binary Floating-Point-Arithmetic.

In JavaScript, NaN is unique, it is not equal to anything, including itself! therefore any comparisons to it will either always yield true or false. Therefore you should use isNaN(/* num */) instead to test if a value is NaN. This rule is aimed at removing this footgun.

# Invalid Code Examples

if (foo == NaN) {
    // unreachable
}
if (NaN != NaN) {
    // always runs
}

# Correct Code Examples

if (isNaN(foo)) {
    /* */
}
if (!isNaN(foo)) {
    /* */
}

# Config

Name Type Description
enforceForSwitchCase bool Switch statements use === internally to match an expression, therefore switch (NaN) and case NaN will never match.
This rule disables uses like that which are always incorrect (true by default)
enforceForIndexOf bool Index functions like indexOf and lastIndexOf use === internally, therefore matching them against NaN will always
yield -1. This option disallows using indexOf(NaN) and lastIndexOf(NaN) (false by default)
More incorrect examples
123 == NaN;
123 === NaN;
NaN === "abc";
NaN == "abc";
123 != NaN;
123 !== NaN;
NaN !== "abc";
NaN != "abc";
NaN < "abc";
"abc" < NaN;
NaN > "abc";
"abc" > NaN;
NaN <= "abc";
"abc" <= NaN;
NaN >= "abc";
"abc" >= NaN;
More correct examples
var x = NaN;
isNaN(NaN) === true;
isNaN(123) !== true;
Number.isNaN(NaN) === true;
Number.isNaN(123) !== true;
foo(NaN + 1);
foo(1 + NaN);
foo(NaN - 1)
foo(1 - NaN)
foo(NaN * 2)
foo(2 * NaN)
foo(NaN / 2)
foo(2 / NaN)
var x; if (x = NaN) { }
foo.indexOf(NaN)
foo.lastIndexOf(NaN)

Source (opens new window)

Last Updated: 11/18/2020, 9:36:33 PM