Can anyone explain how NaN(not a number) is actually a number and NaN==NaN is false | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Can anyone explain how NaN(not a number) is actually a number and NaN==NaN is false

var a=b=1/"n"; console.log(a, b, typeof a, a==b); output>NaN NaN number false

9th Dec 2019, 5:11 PM
I Quit Sololean, Dont Like It Anymore
4 Answers
+ 5
There's this standard that describes how floating point numbers (the ones with a dot like 3.14125..) work. It's called IEEE-754 and in there it says that, for example, `0/0` is a NaN value. I don't know if you have heard about binary before, but let's say a floating point number consists of 32 bits, that means 32 ones and zeroes. IEEE-754 says that if the first 8 bits are 1* then the number is a NaN. That means that NaN is a number, yes? Because it uses the same 32 bits as any other number. Floating point numbers can not only be positive or negative, like 1.2344 or -0.82881, but they can also be NaN, or other special values like Infinity. If, with NaNs, the first 8 bits are 1*, we still have 24 more bits to play with, so there are about 4 million different NaN values. That means if you compare two random NaNs, usally, they will not be equal. Hence (NaN==NaN) == false. ____ * almost true but I am simplifying.
9th Dec 2019, 10:16 PM
Schindlabua
Schindlabua - avatar
+ 6
And some extra info to those that are interested: The javascript standard only has a single number type, unlike most programming languages, which at least have integers and floats. And even if the javascript standard does not specify the bit pattern of a number type value, any number must "behave like an IEEE-754 double precision float". Go figure. What's especially interesting is that if you use for example the binary shift operators, then the number will behave like a 2s complement integral value, even though that's not at all what IEEE-754 floats look like: 5 >> 1; // 2. Why? I haven't looked their reasoning up in the standard but it has always been surprising to me how a single number type can assume two different binary representations depending on which operators you use.
9th Dec 2019, 10:29 PM
Schindlabua
Schindlabua - avatar
0
thanks Mirielle
9th Dec 2019, 6:35 PM
I Quit Sololean, Dont Like It Anymore
0
Thank you so mutch Schindlabua, very well explanation.
9th Dec 2019, 11:41 PM
I Quit Sololean, Dont Like It Anymore