Open In App

How to Check if a Value is NaN ?

Last Updated : 15 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In JavaScript, you can check if a value is NaN using the isNaN() function or by using the Number.isNaN() method. Both methods return a boolean value indicating whether the provided value is NaN.

Using isNaN() function:

isNaN(NaN); // true
isNaN(42); // false
isNaN("Hello"); // true (the string cannot be converted to a number)

Using Number.isNaN() method:

Number.isNaN(NaN); // true
Number.isNaN(42); // false
Number.isNaN("Hello"); // false (the string is not a number, but it's not NaN)

Key Points:

  • isNaN() function returns true if the provided value is NaN or if it cannot be converted into a number. This can sometimes lead to unexpected behavior, such as isNaN("Hello") returning true.
  • Number.isNaN() method returns true only if the provided value is NaN. It does not perform any type coercion, so non-numeric values are considered false.

Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads