Understanding NaN, isNaN() and Number.isNaN()
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.
This is what happens when we do isNaN():
Step3: 12 === NaN?
Step2: isNaN(NaN) // Number("apple") gives NaN
Step3: NaN === 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:
Step1: 12 === NaN
Step1: "apple" === NaN
Step1: NaN === NaN
Step2: 12 === NaN
Step1: isNaN(NaN) // Number("pikachu") returns NaN
Step2: NaN === NaN
I hope you found this article useful. I would love to hear your thoughts. 😇
Thanks for reading. 😊
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’.