Why JavaScript says that a number is not a number? [duplicate]
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
.
Solution 1:
As I understand it, NaN
is a sentinel instance of the Number
class that represents, well, exactly what it stands for - numeric results that cannot be adequately represented. So 0/0
is not a number, in the sense that it's NaN
, but it is a Number
in terms of its type.
Perhaps it should have been called NaRN (Not a Representable Number).
Solution 2:
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.
Solution 3:
You are confusing the type of your object with the value. NaN
is a specific value that a an object of type number
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.
Solution 4:
You should check out the Wikipedia article. It has more details.