This might just be a weird quirk of JavaScript, but I'm curious if anyone knows why this happens:
({} <= {}) => true
({} >= {}) => true
({} == {}) => false
({} === {}) => false
({} > {}) => false
({} < {}) => false
Why are the first two true given that all the others are false?
I thought it may be casting the objects to numbers before comparing, but...
Number({}) >= Number({}) => false
This might just be a weird quirk of JavaScript, but I'm curious if anyone knows why this happens:
({} <= {}) => true
({} >= {}) => true
({} == {}) => false
({} === {}) => false
({} > {}) => false
({} < {}) => false
Why are the first two true given that all the others are false?
I thought it may be casting the objects to numbers before comparing, but...
Number({}) >= Number({}) => false
1 Answer
Reset to default 24Using the <
/<=
/>
/>=
operators in ES5 uses the Abstract Relational Comparison Algorithm, which is a fancy way of saying it coerces the types before comparing them. When {}
is coerced with [[ToPrimitive]]
, it falls back to the toString()
method, which returns "[object Object]"
for both. Because the equals-variants of the less than/greater than operators check equality first, and the strings are equal, the check succeeds. It fails for the non-equality-checking variants because, well, the strings are equal.
==
doesn't use the same coercion algorithm, it uses the Abstract Equality Comparison Algorithm. The first thing this algorithm checks is if the types are the same -- which they are, of course, for two bare objects. Therefore the algorithm proceeds with the first step, and goes down to check f:
Return true if x and y refer to the same object. Otherwise, return false.
Each usage of {}
creates a new object, so this check fails and the result is false.
===
is similar, except there is no coercion step. It fails at step 7, which uses the same language as substep f of the AECA.
tl;dr: >=
/ <=
coerce in a different way than ==
/ ===
.
==
and<=
/>=
. – Pointy Commented Apr 28, 2016 at 22:21==
. – Pointy Commented Apr 28, 2016 at 22:23