ESLint Unexpected use of isNaN

JavascriptEslint

Javascript Problem Overview


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

[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.

Javascript Solutions


Solution 1 - Javascript

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

Solution 2 - Javascript

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

Solution 3 - Javascript

@Andy Gaskell isNumber('1.2.3') return true, you might want to edit your answer and use Number() in place of parseFloat()

    const isEmpty = value => typeof value === 'undefined' || value === null || value === false;
    const isNumeric = value => !isEmpty(value) && !Number.isNaN(Number(value));
  console.log(isNumeric('5')); // true
  console.log(isNumeric('-5')); // true
  console.log(isNumeric('5.5')); // true
  console.log(isNumeric('5.5.5')); // false
  console.log(isNumeric(null)); // false
  console.log(isNumeric(undefined)); // false

Solution 4 - Javascript

In my case, I wanted to treat 5 (integer), 5.4(decimal), '5', '5.4' as numbers but nothing else for example.

If you have the similar requirements, below may work better:

const isNum = num => /^\d+$/.test(num) || /^\d+\.\d+$/.test(num);

//Check your variable if it is a number.
let myNum = 5;
console.log(isNum(myNum))

To include negative numbers:

const isNum = num => /^-?\d+$/.test(num) || /^-?\d+\.\d+$/.test(num);

This will remove your issue of global use of isNaN as well. If you convert the isNum function to a normal ES5 function, it will work on IE browser as well.

Solution 5 - Javascript

For me this worked fine and didn't have any problem with ESlint

window.isNaN()

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionElias GarciaView Question on Stackoverflow
Solution 1 - JavascriptAndy GaskellView Answer on Stackoverflow
Solution 2 - JavascriptthyforhtianView Answer on Stackoverflow
Solution 3 - JavascriptVincent BaronnetView Answer on Stackoverflow
Solution 4 - JavascriptNoby FujiokaView Answer on Stackoverflow
Solution 5 - JavascriptYoannes GeisslerView Answer on Stackoverflow