Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 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.
like image 338
Arseni Mourzenko Avatar asked Jul 09 '10 17:07

Arseni Mourzenko


People also ask

Is JavaScript number a double?

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.

Why are numbers immutable in JavaScript?

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 .

Why is 0 Not-a-Number in JavaScript?

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.


1 Answers

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).

like image 166
Andrzej Doyle Avatar answered Oct 06 '22 18:10

Andrzej Doyle