This code in JS gives me a popup saying ‘i think null is a number’, which I find slightly disturbing. What am I missing?
if (isNaN(null)) { alert('null is not a number'); } else { alert('i think null is a number'); }
I’m using Firefox 3. Is that a browser bug?
Other tests:
console.log(null == NaN); // false console.log(isNaN('text')); // true console.log(NaN == 'text'); // false
So, the problem seems not to be an exact comparison with NaN?
Edit: Now the question has been answered, I have cleaned up my post to have a better version for the archive. However, this renders some comments and even some answers a little incomprehensible. Don’t blame their authors. Among the things I changed was:
- Removed a note saying that I had screwed up the headline in the first place by reverting its meaning
- Earlier answers showed that I didn’t state clearly enough why I thought the behaviour was weird, so I added the examples that check a string and do a manual comparison.
I believe the code is trying to ask, ‘is
xnumeric?’ with the specific case here ofx = null. The functionisNaN()can be used to answer this question, but semantically it’s referring specifically to the valueNaN. From Wikipedia forNaN:In most cases we think the answer to ‘is null numeric?’ should be no. However,
isNaN(null) == falseis semantically correct, becausenullis notNaN.Here’s the algorithmic explanation:
The function
isNaN(x)attempts to convert the passed parameter to a number1 (equivalent toNumber(x)) and then tests if the value isNaN. If the parameter can’t be converted to a number,Number(x)will returnNaN2. Therefore, if the conversion of parameterxto a number results inNaN, it returns true; otherwise, it returns false.So in the specific case
x = null,nullis converted to the number 0, (try evaluatingNumber(null)and see that it returns 0,) andisNaN(0)returns false. A string that is only digits can be converted to a number and isNaN also returns false. A string (e.g.'abcd') that cannot be converted to a number will causeisNaN('abcd')to return true, specifically becauseNumber('abcd')returnsNaN.In addition to these apparent edge cases are the standard numerical reasons for returning NaN like 0/0.
As for the seemingly inconsistent tests for equality shown in the question, the behavior of
NaNis specified such that any comparisonx == NaNis false, regardless of the other operand, includingNaNitself1.