docta_faustus
docta_faustus

Reputation: 2799

null and undefined inconsistent comparison

I'm curious to know why

null == undefined

returns true but

null >= undefined

returns false

Is the inclusion of the greater than operator coercing the values differently?

Upvotes: 8

Views: 578

Answers (2)

voithos
voithos

Reputation: 70552

tl;dr The >= ends up coercing both arguments to numbers in this case: undefined gets coerced to NaN while null gets coerced to 0, which aren't equal. For ==, the spec explicitly defines that null == undefined is true.


The values do, in fact, get coerced in both cases (in a sense, at least - the case with == is special). Let's consider them one at a time, with the help of the spec.

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

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

The last point is the key. From the ToNumber table, we see that undefined gets coerced to NaN, and the algorithm considers any comparison with NaN as being falsy (see steps 3.c. and 3.d.). Thus, null >= undefined is false.


For the other case, ==, the story is actually much simpler: the spec explicitly states that null == undefined is true as part of the "Abstract Equality Comparison Algorithm" (see steps 2. and 3.). Thus, null == undefined is true.

Upvotes: 7

Maksym Kozlenko
Maksym Kozlenko

Reputation: 10363

In JS == operator coerces values to same type to compare, so 1=="1" is true. Use === operator for exact type matching

Upvotes: 0

Related Questions