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?
null is an assigned value. It means nothing. undefined means a variable has been declared but not defined yet.
"undefined" indicates that a variable has been declared but not given a value, while "not defined" indicates that a variable does not exist.
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.
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.
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:
null and undefined already are).Strings (which 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With