Why is isNaN(null) == false in JS?
Asked Answered
A

10

160

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.
Argyrol answered 22/9, 2008 at 15:32 Comment(3)
don't you mean "Why is isNaN(null) == false" ?Guarino
Based on your code, isnan(null) is returning false (null is not "not a number") if it says "I think null is a number".Lathrop
Use Number.isNaN instead.Udela
S
135

I believe the code is trying to ask, "is x numeric?" with the specific case here of x = null. The function isNaN() can be used to answer this question, but semantically it's referring specifically to the value NaN. From Wikipedia for NaN:

NaN (Not a Number) is a value of the numeric data type representing an undefined or unrepresentable value, especially in floating-point calculations.

In most cases we think the answer to "is null numeric?" should be no. However, isNaN(null) == false is semantically correct, because null is not NaN.

Here's the algorithmic explanation:

The function isNaN(x) attempts to convert the passed parameter to a number1 (equivalent to Number(x)) and then tests if the value is NaN. If the parameter can't be converted to a number, Number(x) will return NaN2. Therefore, if the conversion of parameter x to a number results in NaN, it returns true; otherwise, it returns false.

So in the specific case x = null, null is converted to the number 0, (try evaluating Number(null) and see that it returns 0,) and isNaN(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 cause isNaN('abcd') to return true, specifically because Number('abcd') returns NaN.

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 NaN is specified such that any comparison x == NaN is false, regardless of the other operand, including NaN itself1.

Spithead answered 22/9, 2008 at 15:54 Comment(10)
BTW, NaN !== NaN. So, I think, it is not totally correct to say Number('abcd') == NaN because Number('abcd') is NaN but not equal to NaN. I adore JavaScript.Abigail
Yes. I meant to convey that Number('abcd') is NaN but I implied that it tests true for equality, which is not the case. I will edit it.Spithead
I wonder why are isNaN and Number designed to behave that way?Petroleum
The simple answer is that it's designed to have the same semantics as the IEEE 754 floating-point standard.Spithead
Since null is converted to 0, why null == false returns false?Steeve
The conversion of null to 0 only (at least in this context) occurs within the isNaN() function, which coerces its argument.Spithead
Number(null) == 0 but parseInt(null) == NaN love JSTreytri
Note that isNaN(undefined) === true.Willingham
@Treytri parseInt accepts strings; String(null) is "null", which doesn’t start with digits or whitespace followed by digits. parseInt and Number are very different functions.Udela
To put simply - because +null = 0, therefore isNaN(null) = false.Brabazon
F
41

I just ran into this issue myself.

For me, the best way to use isNaN is like so

isNaN(parseInt(myInt))

taking phyzome's example from above,

var x = [undefined, NaN,     'blah', 0/0,  null, 0,     '0',   1,     1/0, -1/0,  Number(5)]
x.map( function(n){ return isNaN(parseInt(n))})
        [true,      true,    true,   true, true, false, false, false, true, true, false]

( I aligned the result according to the input, hope it makes it easier to read. )

This seems better to me.

Francescafrancesco answered 17/12, 2013 at 8:32 Comment(3)
Won't work if myInt="123d". parseInt converts "123d" to 123, which then fails the isNaN test.Skaw
indeed, If you want to catch that scenario as well, I suggest to combine my answer and Glenn's. which will look like this isNaN(parseInt(str,10)) || isNaN(Number()). btw - for me, since I have to run parseInt in order to use the numeric value of the string, allowing "123d" to be considered as valid number is fine. However I see the need to detect that scenario as well.Francescafrancesco
And with the beauty if Typescript, you have to do isNaN(parseInt(String(myInt))) 😂Decimate
G
11

This is indeed disturbing. Here is an array of values that I tested:

var x = [undefined, NaN, 'blah', 0/0, null, 0, '0', 1, 1/0, -1/0, Number(5)]

It evaluates (in the Firebug console) to:

,NaN,blah,NaN,,0,0,1,Infinity,-Infinity,5

When I call x.map(isNaN) (to call isNaN on each value), I get:

true,true,true,true,false,false,false,false,false,false,false

In conclusion, isNaN looks pretty useless! (Edit: Except it turns out isNaN is only defined over Number, in which case it works just fine -- just with a misleading name.)

Incidentally, here are the types of those values:

x.map(function(n){return typeof n})
-> undefined,number,string,number,object,number,string,number,number,number,number
Grind answered 22/9, 2008 at 22:50 Comment(2)
What do you imagine that NaN should mean? What do you think is so misleading about NaN or in testing for it? Why are you disturbed?Titi
Well, this was 8 years ago, but it looks like it I was disturbed that 1) it has inconsistent results for values that aren't of type Number, and 2) it ever returns true for something that isn't of type Number. Because a string is not, in fact, a NaN. (Also see my other answer, which explains why this happens.)Grind
G
11

(My other comment takes a practical approach. Here's the theoretical side.)

I looked up the ECMA 262 standard, which is what Javascript implements. Their specification for isNan:

Applies ToNumber to its argument, then returns true if the result is NaN, and otherwise returns false.

Section 9.3 specifies the behavior of ToNumber (which is not a callable function, but rather a component of the type conversion system). To summarize the table, certain input types can produce a NaN. These are type undefined, type number (but only the value NaN), any object whose primitive representation is NaN, and any string that cannot be parsed. This leaves undefined, NaN, new Number(NaN), and most strings.

Any such input that produces NaN as an output when passed to ToNumber will produce a true when fed to isNaN. Since null can successfully be converted to a number, it does not produce true.

And that is why.

Grind answered 22/9, 2008 at 23:7 Comment(0)
B
4

Null is not NaN, as well as a string is not NaN. isNaN() just test if you really have the NaN object.

Biting answered 22/9, 2008 at 15:33 Comment(2)
But then at least a string is cast into a NaN object, as isNaN("text") returns true.Argyrol
“isNaN() just test if you really have the NaN object” — No, Number.isNaN does that. isNaN coerces its argument to a number, then checks if it is a NaN value.Udela
M
3

In ES5, it defined as isNaN (number) returns true if the argument coerces to NaN, and otherwise returns false.

And see the The abstract operation ToNumber convertion table. So it internally js engine evaluate ToNumber(Null) is +0, then eventually isNaN(null) is false

Mcginnis answered 23/4, 2015 at 11:9 Comment(0)
M
0

I'm not exactly sure when it comes to JS but I've seen similar things in other languages and it's usually because the function is only checking whether null is exactly equal to NaN (i.e. null === NaN would be false). In other words it's not that it thinks that null is in fact a number, but it's rather that null is not NaN. This is probably because both are represented differently in JS so that they won't be exactly equal, in the same way that 9 !== '9'.

Mistakable answered 22/9, 2008 at 15:40 Comment(0)
P
0

The best way to check for null, undefined, 0, '0', etc is using

isNaN(parseFloat(value))

as follows:

const data = [null, undefined, NaN, 0, '0', false, true, 1, 3.14];

const result = data.map(value => isNaN(parseFloat(value)));

console.log('Result: ', result);
Palpitate answered 5/9, 2023 at 2:7 Comment(0)
G
-1

Note:

"1" == 1 // true
"1" === 1 // false

The == operator does type-conversion, while === does not.

Douglas Crockford's website, a Yahoo! JavaScript evangelist, is a great resource for stuff like this.

Grinder answered 23/9, 2008 at 11:50 Comment(0)
A
-2
(NaN == null) // false
(NaN != null) // true

Funny though:

(NaN == true)  // false
(NaN == false) // false
(NaN)          // false
(!NaN)         // true

Aren't (NaN == false) and (!NaN) identical?

Akiko answered 15/6, 2021 at 5:4 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.