We can do:
NaN = 'foo'
as well as
undefined = 'foo'
Why they are not reserved keywords?
Edit 1 (DownVoters):
I think it should be implemented in order to be sure that when we are looking for a
number
, it is anumber
:)If we should use
IsNaN()
ortypeof
so whyNaN
orundefined
are needed?
I'm speculating now, but the reason why I think
NaN
andundefined
are not keywords is because you generally don't assign these values to variables.undefined
basically meansuninitialized
, and if you want to make it clear that the value is unknown you usenull
. Soundefined
usually means not-initialized or the result of JavaScript code gone wrong.NaN
Is rarely assigned manually, simply because you can't do much with this value. It is usually the result of a calculation gone wrong. The makers of JavaScript probably didn't want to give this value the visibility of primitive values.Also,
NaN
is also present in other languages and it isn't used as a keyword there either. For example: InC#
NaN is represented byDouble.NaN
, since you don't make a distinction between floating point and integer values in JavaScript, I'm guessing that's why they putNaN
with the Global Identifiers!I hope this clears things up!
I cannot tell you why, but
undefined
andNaN
are actually properties of the global object:There is a difference between the value
undefined
(NaN
) and the corresponding property.You might notice the
[[Writable]]: false
. I'm not sure whether this new in ES5 (and might not be adapted by all browsers), but in newer browsers (tested in Firefox 6), assigning a new value toundefined
has no effect:So although it seems you can assign a new value, you actually cannot.
Not sure if there was a specific reason to not make them reserved keywords, but it was decided against it. The language still works. You cannot override these values, so it's fine.
The only way to test whether a number is
NaN
, is to useisNaN()
anyway.https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/NaN
https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/undefined
NaN
is not a keyword, but is rather a built-in property of the global object, and as such may be replaced (likeundefined
, but unlike the keyword this or the literalstrue
,false
, andnull
).You can test if a value is NaN with the
isNaN()
function. MoreoverNaN
is defined to be unequal to everything, including itself.Or in a nut shell you can say that:
NaN
is the value returned when you try to treat something that is not a number as a number. For instance the results of 7 times "abc" is not a number. The old form of it is Number.NaN You can test for not-a-number values with theisNaN()
function.Hope this helps.