What is strange about NaN is that it does not equal anything, not even itself. Because of this it makes testing for NaN a little move involved then just using the equality or identity operators. There is a well supported native method called isNaN, but also Number.isNaN both of which work differently, more on that later.
So now that we have some basic ways of knowing how to end up with NaN figured out lets look into the ways to go about knowing if we have a NaN value, and so forth.
This behavior may not be wrong necessarily because in a way values like undefined, and null are Not Numbers also of course. Still it may not really be the behavior that is expected when using a method called isNaN as often the expectation might be that the method should only return true when a value is NaN and only NaN. So with that said lets look at some more options when it comes to finding out if a Value is NaN.
So the Number.isNaN method works as expected if what is expected is for the method to return true only if the given value is NaN and only NaN.
The only problem with Number.isNaN is that it does not work on any version of IE, there is no support at all. So then this might be a reason why you might want to use some kind of user space option for testing for NaN if you care about supporting those older platforms for some reason. With that said lets look at making a user space option as that is nit so hard to do when it comes to working out a quick user space solution.
When going vanilla js style with a project such a method might need to be part of your micro frame work. making a method to do this is not so hard, one way is to just return false if any type other than a Number is given, then convert to a String and test against the String ‘NaN’ in the off chance that the string ‘NaN’ is given then it will return false because it is a String. Whatever something like this.
This seems to behave like that of Number.isNaN, but will work on old browsers. It seems to work okay, but maybe you might prefer to use the method that exists in lodash that makes use of the fact that NaN is the only primitive value that does not equal itself.
Nice slick one liner.
Monkey Patching is generally frowned upon, but generally only if you are extending built in Objects with non standard methods. In this case monkey patching Number.isNaN support is just making sure that something that should be there is there.