Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 977
docta_faustus Avatar asked Dec 03 '15 00:12

docta_faustus


People also ask

What is the relationship between null and undefined?

null is an assigned value. It means nothing. undefined means a variable has been declared but not defined yet.

What is the difference between null undefined and not defined?

"undefined" indicates that a variable has been declared but not given a value, while "not defined" indicates that a variable does not exist.

What is difference between null and undefined and where to use what?

Null: It is the intentional absence of the value. It is one of the primitive values of JavaScript. Undefined: It means the value does not exist in the compiler. It is the global object.

IS null === undefined?

Difference Between undefined and null Though, there is a difference between them: undefined is a variable that refers to something that doesn't exist, and the variable isn't defined to be anything. null is a variable that is defined but is missing a value.


1 Answers

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.

like image 144
voithos Avatar answered Oct 03 '22 09:10

voithos