parseFloat(\"NaN\")
returns \"NaN\", but
parseFloat(\"NaN\") == \"NaN\"
returns false. Now, that\'s probably a go
isNaN
works for all values that aren't numbers
isNaN('foo') == true
isNaN(NaN) == true
isNaN(12) == false
isNaN([1,2,3]) == true
If, however you want to check for NaN
specifically, or avoid type coercion;
you can use Number.isNaN
instead
Number.isNaN('foo') == false
Number.isNaN(NaN) == true
Number.isNaN(12) == false
Number.isNaN([1,2,3]) == false
I'm working with Google Apps Script and so I'm stuck with ECMA 5. Similar to Electric Coffee's answer, here's what I was able to figure out that seems to give a sure answer as to whether or not a value is actually NaN
, not if a value is NaN
but if it is actually NaN
itself:
function isThisNaN(x)
{
return isNaN(x) && Object.prototype.toString.call(x) === '[object Number]';
}
console.log(isThisNaN(NaN)); // true
lol Just funny to me that Object.prototype.toString.call(NaN)
equals '[object Number]'
. My newbie brain tells me that NaN
is "Not a Number" but sadly it's just not that simple.
EDIT: I guess I should have said how I ended up at this article. I went with the idea that surely a string that doesn't contain a number wouldn't be treated as a number... well, I ended up finding this out:
isNaN('a'); // true
isNaN(' '); // false
so even though ' '
is a non-numerical string it apparently gets coaxed into a number (0
).
console.log(Number(' ')); // 0.0
however...
console.log( 0 ? true : false); // false
console.log(' ' ? true : false); // true
After reading more I do understand it a bit better but wow what a mental crapstorm for a newbie lol