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?
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?
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).String
s (which they are not).String
s, 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
.
false
and null
get coerced to +0
. –
Thibaut The Abstract Relational Comparison Algorithm
Wow that's a gob full. Learnt something though, so nice one. –
Jumbala In JS ==
operator coerces values to same type to compare, so 1=="1"
is true
. Use ===
operator for exact type matching
© 2022 - 2024 — McMap. All rights reserved.
undefined
is a variable, that happens to be undefined as long you don't define it – AsymptomaticIs the inclusion of the greater than operator coercing the values differently?
The inclusion of>
means the values DON'T get coerced. – Jumbala