ESLint Unexpected use of isNaN

2022-08-30 01:31:02

I'm trying to use the global function inside an arrow function in a Node.js module but I'm getting this error:isNaN

[eslint] Unexpected use of 'isNaN'. (no-restricted-globals)

This is my code:

const isNumber = value => !isNaN(parseFloat(value));

module.exports = {
  isNumber,
};

Any idea on what am I doing wrong?

PS: I'm using the AirBnB style guide.


答案 1

As the documentation suggests, use Number.isNaN.

const isNumber = value => !Number.isNaN(Number(value));

Quoting Airbnb's documentation:

Why? The global isNaN coerces non-numbers to numbers, returning true for anything that coerces to NaN. If this behavior is desired, make it explicit.

// bad
isNaN('1.2'); // false
isNaN('1.2.3'); // true

// good
Number.isNaN('1.2.3'); // false
Number.isNaN(Number('1.2.3')); // true

答案 2

FYI, this will not work for IE. Check here at browser compatibility.