Understanding NaN, isNaN() and Number.isNaN()
NaN is something which we use less frequently in JavaScript but still it’s worth understanding the concept.
What is NaN?
NaN is a property that represents Not a Number value. We get NaN when we try to do a numeric operation on something which cannot be converted to a Number.
Note: Be careful while using “+” as this can be used for both string concatenation and number addition.
Whenever we perform any numeric operation, JS engine has to make sure that all the elements participating in the operation are either number or can be converted to a number.
In the case of 10*’2', first string ‘2’ is converted into numeric value 2 and then multiplication happens hence we get 20 as result.
But if we do 10*’a’, we get NaN. This is because when JS tries to convert “a” into number, it result in NaN and NaN in operation with any other elements always returns NaN.
What is isNaN()?
isNaN() is a method which can be used to check if the provided value is anything other than number.
isNaN(x) returns true for every value of x other than number or which can be converted to a number.
How isNaN() works?
isNaN first converts the provided value to Number and if its anything other than NaN, it returns false.
A sample pseudo code for isNaN
function isNaN(value) {
// Coerce value to a number
let number = Number(value);
// Check if the result is NaN by using the unique property of NaN
return number !== number;
}
Since JavaScript’s NaN
is the only value in the language that is not equal to itself, this behavior is used to identify NaN
. Internally, isNaN()
can check if a value is NaN
by using value !== value
, as this condition will only be true
for NaN
.
How is this different from Number.isNaN()?
Number.isNaN()
is a method tied up to Number type while isNaN() is a global method.
Number.isNaN() doesn’t convert the value provided to Number, rather it just checks if the value is a literal NaN or not. Which means the Step1 of above code is ignored.
Hence the working becomes:
function Number.isNaN(value) {
return value !== value;
}
I hope you found this article useful. I would love to hear your thoughts. 😇
Thanks for reading. 😊
Cheers! 😃
If you find this article useful, you can show your appreciation by clicking on the clap button. As the saying goes, ‘When we give cheerfully and accept gratefully, everyone is blessed’.