JavaScript isNaN()

Posted by

Function

What is the JavaScript isNaN() Function?

The JavaScript isNaN() function is a built-in function used to determine whether a value is a number. It returns true if the value is NaN (Not a Number) and false if the value is a number.

Syntax

The syntax for the isNaN() function is:

[dm_code_snippet background=”yes” background-mobile=”yes” slim=”no” line-numbers=”no” bg-color=”#abb8c3″ theme=”dark” language=”php” wrapped=”no” height=”” copy-text=”Copy Code” copy-confirmed=”Copied”]

isNaN(value)

[/dm_code_snippet]

The parameter value is the value to be tested.

Example

Below is an example of using the isNaN() function:

[dm_code_snippet background=”yes” background-mobile=”yes” slim=”no” line-numbers=”no” bg-color=”#abb8c3″ theme=”dark” language=”php” wrapped=”no” height=”” copy-text=”Copy Code” copy-confirmed=”Copied”]

let x = 'Hello';

if (isNaN(x)) {
  console.log('x is not a number');
}

[/dm_code_snippet]

In this example, the isNaN() function returns true since the value of x is not a number. The output of this code would be:

[dm_code_snippet background=”yes” background-mobile=”yes” slim=”no” line-numbers=”no” bg-color=”#abb8c3″ theme=”dark” language=”php” wrapped=”no” height=”” copy-text=”Copy Code” copy-confirmed=”Copied”]

x is not a number

[/dm_code_snippet]

Limitations of isNaN()

The isNaN() function has a few limitations that should be aware of:

  • It cannot differentiate between a number and a string that contains a number.
  • It returns true for values that are not actually NaN, for example, an array or an object.

Using Number.isNaN()

In order to overcome the limitations of the isNaN() function, the Number.isNaN() function was introduced in ES6. The syntax for the Number.isNaN() function is:

[dm_code_snippet background=”yes” background-mobile=”yes” slim=”no” line-numbers=”no” bg-color=”#abb8c3″ theme=”dark” language=”php” wrapped=”no” height=”” copy-text=”Copy Code” copy-confirmed=”Copied”]

Number.isNaN(value)

[/dm_code_snippet]

The parameter value is the value to be tested.

The Number.isNaN() function is more reliable than the isNaN() function since it only returns true if the value is actually NaN and not an array or object. It also differentiates between a number and a string that contains a number, where isNaN() would return true for a string containing a number.

Conclusion

The JavaScript isNaN() function is used to determine if a given value is NaN or not. The isNaN() function has some limitations and should be used with caution. For a more reliable solution, the Number.isNaN() function was introduced in ES6 and should be used instead.