How should I understand these?
null>0
> false
null==0
> false
null>=0
> true
How should I understand these?
null>0
> false
null==0
> false
null>=0
> true
When null is used in a numeric experession it evalutes to 0, that explains your > and >= cases.
== is more subtle. Informally, null is not the same as zero, so it kind of makes sense.
The relative comparison operators imply a numeric context, so in those cases (>
, >=
) the null
is converted to a number (zero).
In the ==
case, however, both values are treated as boolean values, and Javascript doesn't think that null
should be equal to any other "falsy" values. It's kind-of weird.
Interesting! It seems like Javascript needs a couple new identity operators like >==
and <==
. Although I am not sure that would make much sense, given the numerical implications of >
and <
.
This gives the expected result...
(null > 0 || null === 0);
The relational operators (>=
and <=
), perform type coercion (ToPrimitive
), with a hint type of Number
, all the relational operators present have this behavior.
You can see the inner details of this process in the The Abstract Relational Comparison Algorithm.
On the other hand, the Equals operator (==
), if an operand is null
it only returns true
if the other is either null
or undefined
, no numeric type coercion is made.
null == undefined; // true
null == null; // true
Check the inner details of this process in the The Abstract Relational Comparison Algorithm.
Recommended articles: