I’ve only been trying it in Firefox’s JavaScript console, but neither of the following statements return true:
parseFloat('geoff') == NaN;
parseFloat('geoff') == Number.NaN;
I’ve only been trying it in Firefox’s JavaScript console, but neither of the following statements return true:
parseFloat('geoff') == NaN;
parseFloat('geoff') == Number.NaN;
As far as a value of type Number is to be tested whether it is a
NaN
or not, the global functionisNaN
will do the workFor a generic approach which works for all the types in JS, we can use any of the following:
For ECMAScript-5 Users:
For people using ECMAScript-6:
And For consistency purpose across ECMAScript 5 & 6 both, we can also use this polyfill for Number.isNan
please check This Answer for more details.
This is not elegant. but after trying isNAN() I arrived at this solution which is another alternative. In this example I also allowed '.' because I am masking for float. You could also reverse this to make sure no numbers are used.
This is a single character evaluation but you could also loop through a string to check for any numbers.
To fix the issue where
'1.2geoff'
becomes parsed, just use theNumber()
parser instead.So rather than this:
Do this:
EDIT: I just noticed another issue from this though... false values (and true as a real boolean) passed into
Number()
return as0
! In which case... parseFloat works every time instead. So fall back to that:And that covers seemingly everything. I benchmarked it at 90% slower than lodash's
_.isNaN
but then that one doesn't cover all the NaN's:http://jsperf.com/own-isnan-vs-underscore-lodash-isnan
Just to be clear, mine takes care of the human literal interpretation of something that is "Not a Number" and lodash's takes care of the computer literal interpretation of checking if something is "NaN".
marksyzm's answer works well, but it does not return false for
Infinity
as Infinity is techinicly not a number.i came up with a
isNumber
function that will check if it is a number.UPDATE: i noticed that this code fails for some parameters, so i made it better.
Simply convert the result to String and compare with 'NaN'.
NaN is a special value that can't be tested like that. An interesting thing I just wanted to share is this
This returns true only for NaN values and Is a safe way of testing. Should definitely be wrapped in a function or atleast commented, because It doesnt make much sense obviously to test if the same variable is not equal to each other, hehe.