Saturday, 16 September 2017

Why is typeof NaN a number?


It's NaN (not a number), but it's typeof is "number". No, really!
Try this:

var iamNaN = 100 * "xyz";

Here, iamNaN becomes NaN for obvious reasons. You cannot expect 100* "xyz" to yield a valid number and so iamNaN gets the value NaN.

However, what's interesting is, typeof iamNaN returns "number". The question is, if iamNaN is NaN (not a number) then how on earth can its data type be a number?

typeof iamNaN; // gives "number"
isNaN(iamNaN); // gives true

Also, why is typeof a string not "number"? After all, a string is also a NaN.

var whyNotMe = "hello";
isNaN(whyNotMe); // gives true

typeof whyNotMe; // yields "string"

iamNaN contains a value that is not a number, and so does whyNotMe. Then why is typeof iamNaN a "number" and not that of whyNotMe?

The ECMAScript standard states that Numbers should be IEEE-754 floating point data. This includes Infinity, -Infinity, and also NaN.

You will find a few more similar arguments floating on the web which tell you why typeof NaN is a "number". This blog however, has a very simple logic to justify the typeof iamNaN to be a "number" and not that of whyNotMe.

Consider this:

What would you call an engineer A, who successfully passes his final exams? A passed engineer or may be just an engineer. Now, what you would you call an engineer B, who just failed his exams? Probably a failed engineer, or may be just an engineer. So, both A and B are engineers, and it just happens that A is a passed engineer and B is a failed engineer. iamNaN (not a number) is like B here. It's a failed number. Just as the typeof B is an engineer (even if failed), the type of iamNaN is a number (even if failed)

In contrast a medical student who passes or fails his exams can never be called a failed engineer. This is exactly why typeof whyNotMe (a string) can never be a "number".

You should now be able to digest the fact that typeof NaN is indeed  a "number"!

isNaN(true) // yields false
Can you guess why?

No comments:

Post a Comment

The HTML Attributes Never Change!

First things first! What is an HTML attribute? The html attributes provide additional information about or to the element . For instan...