Just out of curiosity.
It doesn't seem very logical that typeof NaN
is number. Just like NaN === NaN
or NaN == NaN
returning false, by the way. Is this one of the peculiarities of javascript, or would there be a reason for this?
Edit: thanks for your answers. It's not an easy thing to get ones head around though. Reading answers and the wiki I understood more, but still, a sentence like
A comparison with a NaN always returns an unordered result even when comparing with itself. The comparison predicates are either signaling or non-signaling, the signaling versions signal an invalid exception for such comparisons. The equality and inequality predicates are non-signaling so x = x returning false can be used to test if x is a quiet NaN.
just keeps my head spinning. If someone can translate this in human (as opposed to, say, mathematician) readable language, I would be gratefull.
You've got to love Javascript. It has some interesting little quirks.
http://wtfjs.com/page/13
Most of those quirks can be explained if you stop to work them out logically, or if you know a bit about number theory, but nevertheless they can still catch you out if you don't know about them.
By the way, I recommend reading the rest of http://wtfjs.com/ -- there's a lot more interesting quirks than this one to be found!
NaN
stands for Not a Number. It is a value of numeric data types (usually floating point types, but not always) that represents the result of an invalid operation such as dividing by zero.Although its names says that it's not a number, the data type used to hold it is a numeric type. So in JavaScript, asking for the datatype of
NaN
will returnnumber
(asalert(typeof(NaN))
clearly demonstrates).It is special value of Number type as POSITIVE_INFINITY
Why? By design
Javascript has only one numeric data type, which is the standard 64-bit double-precision float. Everything is a double. NaN is a special value of double, but it's a double nonetheless.
All that
parseInt
does is to "cast" your string into a numeric data type, so the result is always "number"; only if the original string wasn't parseable, its value will be NaN.NaN is a valid floating point value (http://en.wikipedia.org/wiki/NaN)
and NaN === NaN is false because they're not necessarily the same non-number
The ECMAScript (JavaScript) standard specifies that
Numbers
are IEEE 754 floats, which includeNaN
as a possible value.