I have a piece of JavaScript code which is expected to set an integer value to a variable.
Something is broken, so when I try to do alert(A);
, it returns NaN
. isNaN(A);
returns true. But if I alert(typeof(A));
, it says number
.
So how can a variable be a number and not a number at the same time? Maybe I misunderstood what NaN really is?
Edit: thanks to the answers, I see that I was wrong, because:
- The type of
NaN
isNumber
, NaN
does mean "Not a number", which is not the same thing as "not of typeNumber
",0/0
is a good example ofNaN
: it is still a number, but JavaScript (and nobody else) can say what is the real value of zero divided by zero.1/0
on the other hand returnsInfinity
, which is notNaN
.
If you have a variable and assign it the result of 0/0, the variable is still of numeric type, but the value is undefined (not a number). There are other conditions under which this can occur, but this illustrates what you are seeing.
You should check out the Wikipedia article. It has more details.
Along with what has been said I think if you divide by for example a string. It trys to returns NaN but still looks at it as a number.
You are confusing the type of your object with the value.
NaN
is a specific value that a an object of typenumber
can be assigned with, for instance in the case of division of zero by zero or when trying to convert a number from a string that does not represent a number.Some definitions from W3Schools:
Infinity: A numeric value that represents positive/negative infinity
The POSITIVE_INFINITY property represents infinity, returned on overflow. NEGATIVE_INFINITY, represents negative infinity (returned on overflow).
The NaN property represents "Not-a-Number" value. This property indicates that a value is not a legal number.
The isFinite() function determines whether a number is a finite, legal number. This function returns false if the value is +infinity, -infinity, or NaN.
Some tests:
Shows
As I understand it,
NaN
is a sentinel instance of theNumber
class that represents, well, exactly what it stands for - numeric results that cannot be adequately represented. So0/0
is not a number, in the sense that it'sNaN
, but it is aNumber
in terms of its type.Perhaps it should have been called NaRN (Not a Representable Number).