Understanding NaN, isNaN() and Number.isNaN()

Ishwar Rimal
2 min readFeb 27, 2021

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.

This is what happens when we do isNaN():

isNaN("12")
Step1: isNaN(Number("12")
Step2: isNaN(12)
Step3: 12 === NaN?
False
isNaN("apple")
Step1: isNaN(Number("apple")
Step2: isNaN(NaN) // Number("apple") gives NaN
Step3: NaN === NaN
True

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:

Number.isNaN("12")
Step1: 12 === NaN
False
Number.isNaN("apple")
Step1: "apple" === NaN
False
Number.isNaN(NaN)
Step1: NaN === NaN
True
Number.isNaN(Number("12"))
Step1: isNaN(12)
Step2: 12 === NaN
False
Number.isNaN(Number("pikachu"))
Step1: isNaN(NaN) // Number("pikachu") returns NaN
Step2: NaN === NaN
True

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’.

--

--

Ishwar Rimal

Senior FrontEnd Engineer at Intuit. 8 years experience. I write articles on JavaScript, React, Web Optimisation, Startups, Work Life Balance, etc. ❤️ JavaScrip