According to ES5 section 11.9.3 it says that
If Type(x) is Boolean, return the result of the comparison ToNumber(x) == y.
If Type(y) is Boolean, return the result of the comparison x == ToNumber(y).
When I tried to compare
let a = null, b = null;
a == false; // false
b == false; // false
a == ""; // false
b == ""; // false
a == 0; // false
b == 0; // false
What I was expecting here, for a == false
returning false is, false
is coerced to Number which is 0
so the comparison will become a == 0
then for next coercion, which is of type null == 0
, null should get coerced to Number
which is 0
. So finally it should return true for 0 == 0
.
What I got from ES5 11.9.3 is
If x is null and y is undefined, return true.
If x is undefined and y is null, return true.
Mentioned about null and undefined.
The 10th point of the ES 11.9.3 section says that if your comparison doesn't come in above 9 criteria return false
.
Is my comparison returning false
from according to 10th point in ES5 11.9.3 or am I missing something here>
Fundamentally, yes, you're correct that you're getting false
when comparing null
with anything other than null
or undefined
because you get to the last step of the algorithm, which is return false
.
If you're asking why null == false
is false
, the short answer is: Because null
is only ==
null
and undefined
.
The long answer is in the abstract equality operation that you pointed to, here's the up to date version: https://tc39.es/ecma262/#sec-abstract-equality-comparison Steps 1-8 don't apply, but step 9 does:
- If Type(y) is Boolean, return the result of the comparison x == ! ToNumber(y).
(The !
before ToNumber there is not a negation, it's a spec annotation about abrupt completions. This confuses people sometimes.)
So now we have null == 0
. None of Steps 1-12 apply, so the return false
in Step 13 applies.
(I should note that the "If Type(x) is Object" in Step 11 is not true when x
is null
, even though typeof null
is "object"
. The Type operation isn't the same as typeof
, Type(null) is Null.)
In a comment you've said:
I was just curious about null comparisons, so I mentioned all null comparisons in question.
Yes, you're right that you end up getting to the end. The only parts of the algorithm that relate to null
are Steps 2 and 3 that check if one operand is null
and the other operand is undefined
and return true
if so.