NaN in Typescript

NaN in Typescript stands for Not a Number. It is the result of numerical operations, where result is not a number. It is the property of the global object. You can refer it either as NaN or Number.NaN. The typeof NaN is primitive number. We can check whether a value is NaN by using the isNaN function or by Number.IsNan method.

NaN

NaN can happen in several ways.

  • Converting an Invalid value to a number
  • Dividing Zero by Zero
  • Operations involving infinity
  • All Operations involving NaN

Converting an Invalid value to a number

In this following case, we are trying to convert a string to a number. Since “test” cannot be converted to a number it results in a NaN.

Or using an invalid value in any function that expects a number. For Example Math.round or parseInt methods

Converting Undefined into a number

Dividing Zero by Zero

Example

Operations involving infinity

Multiply an Infinity by Zero or divide Infinity by Infinity will result in NaN. Subtracting Infinity by Infinity also results in NaN.

Operations involving NaN

All operations involving NaN results in a NaN.

Comparing NaN

Any comparison between the two NaN's always results in false. NaN is never equal to itself.

In the following example, n1 & n2 are NaN's. But they are neither equal or greater or lesser from each other.

How to check if the value is NaN

There are two ways in which we can check if the value is NaN. One is using the isNan function and the other is to use the Number.isNaN method.

IsNaN

We can check whether a value is NaN by using the global IsNaN method.

But, if you use this function to check a non-numeric value like string. Typescript compiler throws an error here. But code compiles and isNaN tries to convert the “test” into a number, which results in a NaN value. Hence the output is true.

Number.IsNaN

You can also use the Number.IsNaN method, But it does not forcefully convert the parameter to a number. If the argument is not a number, then it results false.

Booleans are not NaN

Booleans are implemented as numerical values with a single binary digit (i.e., 0 & 1). Hence they are treated as numbers.

Summary

When a proper number cannot be the result of numerical operations, then the result is NaN. For Example, converting a string to a number. NaN is a primitive number. The NaN can appear when you convert an Invalid value to a number, Divide Zero by Zero, Some operations involving infinity & all Operations involving NaN, etc. You can check if the value is NaN by using the method IsNaN or Number.IsNaN

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top