Null and undefined inconsistent comparison

I'm curious to know why

null == undefined 

returns true but

 null >= undefined 

returns false

Is the inclusion of a larger number than the operator changing the values ​​differently?

+6
source share
2 answers

tl; dr >= in this case forces both arguments to numbers: undefined forced to NaN , and null forced to 0 , which aren’t equal. For == specification explicitly states that null == undefined is true .


Values ​​are actually typed in both cases (in a sense, at least the case with == is special). Let's look at them one at a time using the specification.

The algorithm for the >= operator uses the "Abstract Relational Comparison Algorithm" , which is shared by other relational operators. The description in the specification shows that the algorithm does the following:

  • Converts arguments to primitives (which null and undefined already exist).
  • Checks if the arguments are String (which they are not).
  • If they are not String s, the algorithm converts the arguments to numbers (see steps 3.a. and 3.b.) and performs a comparison with the results.

The last point is the key. From the ToNumber table ToNumber we see that undefined forced to NaN , and the algorithm considers any comparison with NaN be false (see Steps 3.c. and 3.d.). So null >= undefined is false .


In the other case, == story is actually much simpler: the specification explicitly indicates that null == undefined is true as part of the abstract equality Comparison Algorithm "(see Steps 2 and 3.). Thus, null == undefined is true .

+6
source

In JS == operator matches values ​​for the same type for comparison, so 1=="1" is true . Use the === operator for exact type matching

0
source

All Articles