A Beginner's Guide To "NAN"

A Beginner's Guide To "NAN"

What is "NAN"?

NAN stands for "Not A Number". What does it mean? It simply means the value which is not a number is NAN. There are different operations in JavaScript which return NAN . We will try to explore some of them in this article.

Data Type Of NAN:

It is basically a number type. Though it represents a value that is not a real number.

console.log(typeof NaN); //number

Some Inside About NaN:

One of the interesting properties of NAN is it doesn't equal to any value including itself.

console.log(NaN === NaN); //false
console.log(NaN === false); //false

Now let's try to understand which value/operations return this "NAN" value?

1. console.log(Infinity - Infinity); //NaN
2. console.log(Infinity / Infinity); //NaN
3. console.log(0 / 0); //NaN
4. console.log(0 * undefined); //NaN
5. console.log(parseFloat("hello")); //NaN
6. console.log(Number("hello")); //NaN

These are some examples where we can get a NaN type. In the first four examples, we get some indeterminate results. So indeterminate values return NaN. In the last two examples, the parsing of a string to number returns NaN. Though the below one is acceptable, the above is not.

console.log(parseInt("1.5")); // 1

There are also some cases where JavaScript returns NaN. If we pass some invalid value as arguments of Math functions then also it returns NaN.

1. console.log(Math.log10(-1)); //NaN
2. console.log(Math.pow(-10, 3.5)); //NaN
3. console.log((-10) ** 0.8); //NaN

Now let's see another example

console.log(NaN ** 0);  //1
console.log(Math.pow(NaN, 0)); //1

Is it surprising to you? So let me try to explain it. Whenever we use exponentiation (**) or "Math.pow()" method, with an exponent of 0 it immediately returns 1 without checking the value of the base (which is NaN in this case).

isNaN() vs Number.isNaN() :

1. console.log(isNaN({})); //true
2. console.log(Number({})); //NaN

isNaN() method first converts the empty object to the number and then it checks if it is NaN or not. As we can see in the second line while we convert the empty object to a Number, it returns NaN.

console.log(Number.isNaN({})); //false

Number.isNaN() method just checks the value is NaN or not. It does not convert it to number. So I hope this example helps you to understand the difference between them.

It is advisble to use Number.IsNaN() instead of using isNaN().

Conclusion:

This is just a beginner's guide to NaN in JavaScript. There are lots of things to explore. If you want to learn more about NaN please check the resources below.

  1. MDN

  2. JAVASCRIPT.INFO

  3. ARTICLE BY Dmitri Pavlutin

If this article is helpful to you please let me know about it in the comment section.