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:
NaN
is Number
,NaN
does mean "Not a number", which is not the same thing as "not of type Number
",0/0
is a good example of NaN
: 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 returns Infinity
, which is not NaN
.The JavaScript Number type is a double-precision 64-bit binary format IEEE 754 value, like double in Java or C#. This means it can represent fractional values, but there are some limits to what it can store. A Number only keeps about 17 decimal places of precision; arithmetic is subject to rounding.
They are immutable because they are copied by value. var x = 4; x += 1; you haven't changed the number 4 into the number 5 . You have changed the value stored in the variable x from 4 to 5 .
In JavaScript “0” is equal to false because “0” is of type string but when it tested for equality the automatic type conversion of JavaScript comes into effect and converts the “0” to its numeric value which is 0 and as we know 0 represents false value. So, “0” equals to false.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With