Search code examples
javascriptjavascript-objects

JS objects equality


I am trying to play with objects alongside with Symbol.toPrimitive symbol in order to convert objects to primitives.

I used this code:

function UserEq(name) {
    this.name = name;
    this[Symbol.toPrimitive] = function (hint) {
        alert("hint is: " + hint);
        return 0;
    };
}
function objectEqualityCheck() {
    let user1 = new UserEq("John");
    let user2 = new UserEq("Rambo");

    if (user1 == user2) alert("Equal!");
}

And I expect two conversions resulting in alert Equal!, but that is not what's hapenning...

When used like user1 == 0 all works fine (conversion is to number though).

Why when two objects are compared, it does not work?

EDIT: it doesn't work with === as well.


Solution

  • The first rule in the docs for == defines this

    The comparison x == y, where x and y are values, produces true or false. Such a comparison is performed as follows:

    If Type(x) is the same as Type(y), then
        Return the result of performing Strict Equality Comparison x === y.
    

    TC39


    user1 == user2
    

    Here you're comparing same type so there's no type conversion happens at all


    ToPrimitive is called only under these conditions

    • If Type(x) is either String, Number, or Symbol and Type(y) is Object, return the result of the comparison x == ToPrimitive(y).
    • If Type(x) is Object and Type(y) is either String, Number, or Symbol, return the result of the comparison ToPrimitive(x) == y.