NaN? isNaN? Who's NaN👵? Checkin' out JavaScript NaNs the right way.

NaN? isNaN? Who's NaN👵? Checkin' out JavaScript NaNs the right way.

NaN or Not a Number is a special value which JavaScript automatically assigns to a variable when it gives up solving Math problems.

Bit of a background

The type of the value NaN is a Number.

It occurs more often when both numerator and denominator are zero. Let's take an example of year over year sales growth calculation.  

growthRate = ((currentYear/previousYear) - 1) * 100
Eg.
currentYear = $2,100;
previousYear = $2,000;
((2100/2000) - 1) * 100 = 5% Y/Y Growth

Ha! that's a nice 5% growth 💰. But once a year sales cycle resets with new financial year and when comparing like for like with the previous year, both values will be returned as zeros (at least for the first week) and that's when the NaNs dance all over your app. It can also happen if we do mathematical calculations with alphabets. But that can be ignored if you check datatypes reliably. Please refer this post if you like to reliably check datatypes.

Reliable way to check datatypes in JavaScript
Many versions have come & gone, but this one liner is always a winner!

Solving dancing NaNs

So how can we check for NaNs the right way? Can we use the isNaN() function that comes with JavaScript? The answer is NO!

The problem with isNaN() is that it's not only going to return true for NaN but it's also going to return true for undefined and {} empty object. This makes it very unreliable.

Weirdly, the only value which does not equal itself to is NaN. It's kind of a hack but that's the only way to solve it in ES5 which works on all versions of the browsers. Alternatively, you can use ES6's Number.isNaN() which offers robust NaN checking but it needs Babel compiler for frontend projects.

Please go ahead and replace isNaN() function globally. I am sure you cannot break it more 😂!

PS: This question will be asked in most JavaScript interviews in many tricky ways!

Show Comments