Reputation: 267
I am confuse for these comparison and I don't know how can be happen. in bottom code when I compare x and y for less than or great than, it return false but when I compare them with equals they return true! do you know why this happen?
var x = { y: 10 };
var y = { y: 11 };
x < y; // false
x == y; // false
x > y; // false
x <= y; // true
x >= y; // true
Upvotes: 2
Views: 129
Reputation: 267
now I understand how are x <= y and y <= x resulting in true however x < y and x == y and x > y are all false. in continue of accepted answer I can say these happen because the spec says for x <= y , it will actually evaluate y < x first, and then negate that result. Since y < x is also false, the result of x <= y is true.
Upvotes: 1
Reputation: 29312
x < y; // false
x > y; // false
When any operand of a relational operator is an object, it is converted to a primitive value. So in this case, both x
and y
are first converted to primitive values and then compared with each other.
Both x
and y
will be converted to primitive values by eventually calling .toString()
method on each object which will return a string of the form: [object Object]
and since both objects will be converted in this string form, x < y
and x > y
both evaluate to false because both strings, i.e. [object Object]
are equal.
x == y; // false
This evaluates to false because when types of both operands of ==
operator are same, javascript performs strict equality comparison ===
, and as both objects are two separate objects in memory, they are not equal.
x <= y; // true
x >= y; // true
These both expressions evaluate to true because the following comparison
"[object Object]" == "[object Object]"
evaluates to true.
Upvotes: 2