I’ve only been trying it in Firefox’s JavaScript console, but neither of the following statements return true:
parseFloat(\'geoff\') == NaN;
parseFloat(\'ge
If your environment supports ECMAScript 2015, then you might want to use Number.isNaN to make sure that the value is really NaN.
The problem with isNaN is, if you use that with non-numeric data there are few confusing rules (as per MDN) are applied. For example,
isNaN(NaN); // true
isNaN(undefined); // true
isNaN({}); // true
So, in ECMA Script 2015 supported environments, you might want to use
Number.isNaN(parseFloat('geoff'))
Found another way, just for fun.
function IsActuallyNaN(obj) {
return [obj].includes(NaN);
}
The exact way to check is:
//takes care of boolen, undefined and empty
isNaN(x) || typeof(x) ==='boolean' || typeof(x) !=='undefined' || x!=='' ? 'is really a nan' : 'is a number'
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
It seems that isNaN() is not supported in Node.js out of the box.
I worked around with
var value = 1;
if (parseFloat(stringValue)+"" !== "NaN") value = parseFloat(stringValue);
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?