+ 2

Inconsistencies with Javascript isNaN()

I've just been reading that there are apparently some inconsistencies with how isNaN handles things and is therefore not completely reliable. Strange. In ES6 Number.isNaN() has some improvements over the built in isNaN() in that regard. However, I did a few quick tests: var a = Number.isNaN(1); // false var b = isNaN("hi"); // true var c = Number.isNaN("hi"); // false <<< should be true! var d = isNaN(NaN); // true var e = Number.isNaN(NaN); // true console.log(a, b, c, d, e) It seems that there are still inconsistencies. So, is there some other solution to test for numbers? I've thought of these things but I wonder if there are some other methods. Possible Solution to inconsistencies with isNaN: - use parseFloat(). It will result in NaN if not a number. Question: is it fast? - all numbers should be divisible by one. A `string` or `NaN` will result in `NaN` when divided by 1.

26th Mar 2018, 12:36 PM
dCook
dCook - avatar
3 Answers
+ 4
There is more. Returns false only on number. Number.isNaN(parseInt("hi")) //returns true Number.isNaN(parseInt(NaN)) //returns true Number.isNaN(parseInt(10)) //returns false
26th Mar 2018, 2:17 PM
Toni Isotalo
Toni Isotalo - avatar
+ 3
It's not issue or inconsistency, it's specific behaviour ^^ isNaN(arg) global function test if argument converted to Number is NaN; Number.isNaN(arg) method test if argument is NaN, and nothing else... So, contrarly to what you wrote in your question: Number.isNaN("hi"); // shouldn't be true, as "hi" is a String and is not equal to the NaN special value ^^
26th Mar 2018, 2:46 PM
visph
visph - avatar
0
@toni Looks like a good solution!
26th Mar 2018, 2:23 PM
dCook
dCook - avatar