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 === NaNUse the isNaN function to compare with NaN.) {
showError();
}example.js1 problem
switch (price) {
case NaN:'case NaN' can never match. Use Number.isNaN before the switch.
showError();
break;
case 0:
showFree();
break;
}example.jsNo problems
const price = Number(input);
if (Number.isNaN(price)) {
showError();
} else if (price === 0) {
showFree();
}Options#
| Option | Default | What it does |
|---|---|---|
enforceForSwitchCase | true | Report switch (NaN) and case NaN:. |
enforceForIndexOf | false | Also 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 problemconst hasBadPrice = prices.indexOf(NaN)Array prototype method indexOf cannot find NaN. !== -1;includes and findIndex can find NaN:
example.jswith
{ "enforceForIndexOf": true }No problemsconst hasBadPrice = prices.includes(NaN);
const firstBadPrice = prices.findIndex(Number.isNaN);