DEV Community

bigr0033
bigr0033

Posted on

isNaN() & Number.NaN()

This tutorial will explain how to use the Number.isNaN() method and the global isNaN() function.

NaN (Not a Number)

NaN is the result of operations that have an undefined numerical result.

Examples

  • Converting a non-numeric string into a number
  • Any operation involving NaN itself.

Image description

Strangely enough Numbers contains NaN.

Image description

The important thing to note is that NaN is indeed a numeric data type but it has an undefined numeric value.

isNaN()

The Global isNaN() function checks to see if a value is equal to NaN. This function will return true if the value is NaN. Otherwise it will return false.

For example:

Syntax

isNaN(value)

Parameters

value - The value being compared to NaN.

Returns

A Boolean: true if the value is NaN, otherwise it will return false.

Example

Image description

When the value being evaluated is not of the Number data type this function first attempts to coerce it to being a Number type and then it determines whether it’s NaN so you may find some strange results.

Image description

Number.isNaN()

The Number.isNaN() method evaluates if a value if of the Number data type AND If it is NaN. This method will return true only if the value is NaN with the Number type, otherwise it will be false. This method will not convert its parameter value type to be Number.

Syntax

Number.isNaN(value)

Parameters

value - The value being compared to NaN

Returns

A Boolean: true if the value is NaN and its type is Number , otherwise it will return false.

Example

Image description

The key distinction here is that the global isNaN() is changing its parameter to a Number first and then making the comparison. Number.isNaN() will simply return false on the basis that the value doesn't match the data type requirement before even attempting to check isNaN().

Top comments (0)