use-isnan

Require Number.isNaN() instead of a comparison with NaN

error by defaulthas suggestions

NaN isn't equal to anything, not even itself. value === NaN is always false, value !== NaN is always true, and <, >, <= and >= with NaN are always false.

The rule reports comparisons with NaN and Number.NaN. It also reports switch (NaN) and case NaN:, which can never match.

For ==, ===, != and !==, the report comes with a suggestion that rewrites the comparison to Number.isNaN().

This rule is on by default.

Configure#

On by default as an error. To turn it off:

bunfig.toml
[lint.rules]
"use-isnan" = "off" # or "warn"

Every option, set to its default:

bunfig.toml
[lint.rules]
"use-isnan" = ["error", {
  enforceForSwitchCase = true,
  enforceForIndexOf = false,
}]

Examples#

example.js1 problem
const price = Number(input);

if (price === NaN) {
  showError();
}
example.js1 problem
switch (price) {
  case NaN:
    showError();
    break;
  case 0:
    showFree();
    break;
}
example.jsNo problems
const price = Number(input);

if (Number.isNaN(price)) {
  showError();
} else if (price === 0) {
  showFree();
}

Options#

OptionDefaultWhat it does
enforceForSwitchCasetrueReport switch (NaN) and case NaN:.
enforceForIndexOffalseAlso report indexOf(NaN) and lastIndexOf(NaN) called as methods. They compare with ===, so they always return -1.

Reported with enforceForIndexOf:

example.jswith { "enforceForIndexOf": true }1 problem
const hasBadPrice = prices.indexOf(NaN) !== -1;

includes and findIndex can find NaN:

example.jswith { "enforceForIndexOf": true }No problems
const hasBadPrice = prices.includes(NaN);
const firstBadPrice = prices.findIndex(Number.isNaN);