Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is an object greater/less than or equal to a different object?

Tags:

javascript

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

like image 679
Bryan Downing Avatar asked Apr 28 '16 22:04

Bryan Downing


People also ask

How do you compare two objects?

The equals() method of the Object class compare the equality of two objects. The two objects will be equal if they share the same memory address. Syntax: public boolean equals(Object obj)

How do you know if objects are equal?

If the two objects have the same values, equals() will return true . In the second comparison, equals() checks to see whether the passed object is null, or if it's typed as a different class. If it's a different class then the objects are not equal.

What does >= mean in JavaScript?

The greater than or equal operator ( >= ) returns true if the left operand is greater than or equal to the right operand, and false otherwise.

What is == and === in JavaScript?

== in JavaScript is used for comparing two variables, but it ignores the datatype of variable. === is used for comparing two variables, but this operator also checks datatype and compares two values. Checks the equality of two operands without considering their type. Compares equality of two operands with their types.


1 Answers

Using 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 == / ===.

like image 198
vgel Avatar answered Oct 24 '22 04:10

vgel