DEV Community

Meg Meyers
Meg Meyers

Posted on

JavaScript NaN - advanced JS interview question

In JavaScript, NaN means "not a number." If you run

typeof NaN // number

you will get "number" because NaN is used to define a number that really isn't a number.

Many times when we code we need to be sure that the data type we are working with is actually a number. JS has a built in method called isNaN that will accept any input and let you know if it's not a number. Let's take a look at a few examples:

isNaN(1)    // false   1 is not not a number

isNaN("A")   // true   "A" is not number

isNaN("1")   // false  "1" is not not a number ..... wait what? 
Enter fullscreen mode Exit fullscreen mode

The string "1" is a number? That's what JS is telling us. But anything in quotation marks is for sure Not a Number because anything in quotation marks is a string. If you run typeof "1" you will get string. The thing to understand here is that isNaN is doing implicit coercion "behind the scenes." It is first calling Number("1"), which turns "1" into 1, and then running isNaN(1).

isNaN(Number("1"))    // false because it is a number now that it's been coerced.
Enter fullscreen mode Exit fullscreen mode

Great, so basically isNaN isn't going to be very useful unless we are 100% sure of the input type, but in a dynamically typed language, how can you ever really be sure? That's exactly why we need a foolproof way to check. Is there a way to guarantee that some input is truly not a number? Yes, and we can really impress our interviewers by showing them our deep understanding of JS.

Firstly, in JS, anything compared to itself is true.

a = 1;
a === a;   //true 
b = "B";
b === b;   // true
Enter fullscreen mode Exit fullscreen mode

and NaN compared to anything else will be false.

NaN === 1   // false  
NaN === false    // false
NaN === "b"   // false


Enter fullscreen mode Exit fullscreen mode

Ok. So far so good. This makes perfect sense. So NaN compared to itself is going to be true then, right? Nope.

NaN === NaN    //false
Enter fullscreen mode Exit fullscreen mode

What? Ok, that's weird, but could we use this to our advantage to ensure something is a number? If we know that only in this one situation of something being NaN will the comparison to itself fail, we can simple compare any variable in question to itself with the !== operator and if we get "true" we know that our input is NaN.

a = 1
a !== a  // false because 1 === 1

a = NaN
a !== a   // true
Enter fullscreen mode Exit fullscreen mode

If 'a' is anything other than NaN, the !== will always be false. But due to the strange truth that NaN === NaN is false, a !== a will be true.

Your deep knowledge of the inner workings of JS will surely impress! Now go use Number.isNaN(). It's far more readable and understandable.

Top comments (0)