DEV Community

Cover image for NaN & isNaN

NaN & isNaN

surya profile image surya ・2 min read

This blog post is all about NaN & isNaN in javaScript.

what is NaN?

The NaN property in the global object represents "Not a Number" value.This property indicates that a value is an invalid number.NaN is the return value from operations which have an undefined numerical result.

Interesting facts about NaN

  • NaN is the only thing in javascript that is not equal to itself. Because IEEE declared NaNs are not equal to each other.
  • NaNs are part of IEEE 754 spec, which is a numerical representation specification. so, the type of a NaN is number.
NaN === NaN    //false
typeof NaN     //number
Enter fullscreen mode Exit fullscreen mode

NaN with any mathematical operation is always NaN.

10 - "Maguire" //NaN
Enter fullscreen mode Exit fullscreen mode

In the above code, the string is coerced to a number which is invalid(NaN). so, it returns NaN.

utilities which determine if the value is NaN:

  • isNaN()
  • Number.isNaN()
isNaN(5)       //false
isNaN("Tobey") //true
Enter fullscreen mode Exit fullscreen mode

When we pass a number, it returns false and true for NaN.
But, "Tobey" is not NaN, its a string. The isNaN() utility coerces the value to numbers before it checks. so, the string "Tobey" is coerced to numbers. which is an invalid number(NaN). so, it outputs true. It was considered a bad idea. so, a new utility was introduced in ES6.

A better utility: 🤓

  • Number.isNaN()

It doesn't do any coercion. And it outputs true if the passed value is NaN and its type is Number.

const returnString = () => 'Bully Maguire'
const returnNaN = () => NaN

isNaN(returnString()) ? true : false            //true
isNaN(returnNaN()) ? true : false               //true

Number.isNaN(returnString()) ? true : false     //false
Number.isNaN(returnNaN()) ? true : false        //true
Enter fullscreen mode Exit fullscreen mode

The above example tells the difference between isNaN and Number.isNaN.

And I hope you learned something useful. Thanks a lot 🙏

Discussion (1)

Editor guide
codemonkey51 profile image

Interesting 🤔