NaN or Number.isNaN

Mohit Popli
2 min readApr 7, 2021

Is it a valid number or NaN (Not a number)?? How do I identify if my result of some computation is/will be a valid number. This is something that always keep bugging javascript developers.

Brief description about NaN for those who are not familier with it or haven’t encountered such situations. NaN is basically a result of some arithmetic operation in javascript that turns out to be some non representable value in JS. It might be the outcome of some invalid coercion attempt.

NOTE: Do not confuse NaN values with overflow situations.

5/0 // Infinity0/0 // NaN

Well there’s nothing wrong if you struggle with it. As it’s the candidate in javascript which is not equal to itself!!! Guess who’s that? It’s NaN (Most beloved 3 letter word)

NaN === NaN // false
NaN

Javascript provides 2 ways to solve this misery Number.isNaN() and isNaN(). Let’s see why these are necessary and under what circumstances we should use either of them depending upon our use case.

isNaN('15L') // trueNumber.isNaN('15L') // false

🧐 wait what!! Former returned true whereas latter returned false for the same value. See this is the beauty of javascript well no dark magic exist!!

Let’s break our examples and understand what happens behind the scenes,

When we did isNaN(‘15L’), JS interpreted it as

isNaN(Number('15L'))Number('15L') // NaNisNaN(NaN) // true

But when we did Number.isNaN(‘15L’), JS doesn’t forcefully tried to convert it into Number type rather it simply checks ‘15L’ has primitive type as string that doesn’t turns out to be a NaN as a result returns false. Remember definition of NaN (a value that cannot be represented by any primitive value).

So we can clearly see the difference between both of our guys ,

  1. IsNaN: It will be going to return true if value is currently NaN or if it’s going to be NaN after coercion.
  2. Number.isNaN: This will only return true if the value is currently NaN.

However with latter meaning of NaN remains the same i.e. it should not be invalid number, but it is more reliable way to test against NaN as it doesn’t suffers with the problem of implicit coercion and you can pass values safely that will convert to NaN but actually doesn’t meet the definition of NaN.

Hope it clears the confusion between when/why/where to use these 2 utilities to safeguard your app against NaN.

Sharing is caring!! Happy coding 😊

--

--

Mohit Popli

Software Engineer @Malaysia | Innovator | @twitter m_popli5 | @insta m.popli5