totn JavaScript

JavaScript: Number isNaN() method

This JavaScript tutorial explains how to use the Number method called isNaN() with syntax and examples.

Description

In JavaScript, isNaN() is a Number method that is used to return a Boolean value indicating whether a value is of type Number with a value of NaN. Because isNaN() is a method of the Number object, it must be invoked through the object called Number.

Syntax

In JavaScript, the syntax for the isNaN() method is:

Number.isNaN(value);

Parameters or Arguments

value
The value to test whether it is of type Number with a value of NaN.

Returns

The isNaN() method returns true if the value is NaN and of type Number. Otherwise, it returns false.

Example

Let's take a look at an example of how to use the isNaN() method in JavaScript.

For example:

console.log(Number.isNaN(NaN));
console.log(Number.isNaN(6.7));
console.log(Number.isNaN('6.7'));

In this example, we have invoked the isNaN() method using the Number class.

We have written the output of the isNaN() method to the web browser console log, for demonstration purposes, to show what the isNaN() method returns.

The following will be output to the web browser console log:

true
false
false

In this example, the first output to the console log returned true since the value is NaN.

The second output to the console log returned false since 6.7 is not equal to NaN.

The third output to the console log returned false since the string value '6.7' is not equal to NaN.

Using isNaN() method to determine if a value is a number

You can use the isNaN() method to determine if a value is a number or not.

For example:

var totn_number = Number('ABC123');

if (Number.isNaN(totn_number)) {
    console.log('Value is not a number');

} else {
    console.log('Value is a number');
}

The following will be output to the web browser console log:

Value is not a number

In this example, totn_number will have a value of NaN since 'ABC123' is not a number. Therefore, 'Value is not a number' is output to the console log.

Using isNaN() method with Other Functions

You can also use the isNaN() method to evaluate the output of other functions in JavaScript.

The following Math functions can output NaN as a result:

Let's look at how you might use the isNaN() method to evaluate the output from the abs() method when a non-numeric value is passed in as a parameter.

For example:

var totn_number = 'ABC123';

if (Number.isNaN(Math.abs(totn_number))) {
    console.log('abs parameter was not a number');

} else {
    console.log('abs parameter was a number');
}

The following will be output to the web browser console log:

abs parameter was not a number

In this example, the parameter passed into the abs() method was the value 'ABC123' which is not a number (NaN). This causes the isNaN() method to return true and output 'abs parameter was not a number' to the console log.