In JavaScript, NaN is a valid value of the number type.
console.log(typeof NaN); // number
When prompted to verify if a value matches NaN or not, you’ll encounter an irony: NaN doesn’t equate to itself. Therefore, standard equality comparisons are ineffective for checking NaN values.
if(NaN === NaN){
console.log("NaN is equal to NaN");
}
else {
console.log("NaN is not equal to NaN");
}
Besides, NaN is neither greater nor smaller than any other numeric value.
if(NaN === NaN){
console.log("NaN is equal to NaN");
}
else {
console.log("NaN is not equal to NaN");
}
if(NaN > NaN){
console.log("NaN is Greater to NaN");
}
else {
console.log("NaN is not Greater to NaN");
}
if(NaN < NaN){
console.log("NaN is Smaller to NaN");
}
else {
console.log("NaN is not Samller to NaN");
}
You get below output,

So, how do you check for the value of NaN? There are two ways to check for the value of NaN.
- isNaN()
- Number.isNaN()
Let us first learn about isNaN(). This function checks for the NaN in these two steps,
- Converts the given value to a number
- Check whether the converted value is NaN or not.
So, if you check on the following
console.log(isNaN(undefined)); // true
console.log(isNaN(null)); // false
console.log(isNaN(true)); // false
console.log(isNaN("100")); // false
Surprisingly, it returns false for null, true, and “100” because it can convert them to a number.
The other approach is using the Number.isNaN().
- It does not convert the given value to a number
- It directly checks whether the given value is NaN or not
So, if you check the following,
console.log(Number.isNaN(undefined)); // false
console.log(Number.isNaN(null)); // false
console.log(Number.isNaN(true)); // false
console.log(Number.isNaN("100")); // false
You will get the expected result. My suggestion is to use Number.isNaN() to check for the value of NaN.
Discover more from Dhananjay Kumar
Subscribe to get the latest posts sent to your email.
One thought on “Which is more suitable to use, isNaN or Number.isNaN() in JavaScript”