I’ve only been trying it in Firefox’s JavaScript console, but neither of the following statements return true:
parseFloat('geoff') == NaN; parseFloat('geoff') == Number.NaN;
The Number. isNaN() method returns true if the value is NaN , and the type is a Number.
Check for NaN with self-equality In JavaScript, the best way to check for NaN is by checking for self-equality using either of the built-in equality operators, == or === . Because NaN is not equal to itself, NaN != NaN will always return true .
isnan() isNaN() method returns true if a value is Not-a-Number. Number. isNaN() returns true if a number is Not-a-Number.
JavaScript isNaN() Function The isNaN() function is used to check whether a given value is an illegal number or not. It returns true if value is a NaN else returns false. It is different from the Number. isNaN() Method.
Try this code:
isNaN(parseFloat("geoff"))
For checking whether any value is NaN, instead of just numbers, see here: How do you test for NaN in Javascript?
I just came across this technique in the book Effective JavaScript that is pretty simple:
Since NaN is the only JavaScript value that is treated as unequal to itself, you can always test if a value is NaN by checking it for equality to itself:
var a = NaN; a !== a; // true var b = "foo"; b !== b; // false var c = undefined; c !== c; // false var d = {}; d !== d; // false var e = { valueOf: "foo" }; e !== e; // false
Didn't realize this until @allsyed commented, but this is in the ECMA spec: https://tc39.github.io/ecma262/#sec-isnan-number
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With