How to Check if a Value is NaN ?
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 returnstrue
if the provided value isNaN
or if it cannot be converted into a number. This can sometimes lead to unexpected behavior, such asisNaN("Hello")
returningtrue
.Number.isNaN()
method returnstrue
only if the provided value isNaN
. It does not perform any type coercion, so non-numeric values are consideredfalse
.