2

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.

7
  • 2
    Because they are two different objects in two different spaces in memory. They are not the same object in the same allocated memory space, so by default object comparison, they are not equal Commented Sep 4, 2019 at 18:21
  • @Taplar Oh, I thought that == operator would make implicit conversion. Commented Sep 4, 2019 at 18:21
  • 2
    conversion occurs when you try to match two different type not when they are of same type Commented Sep 4, 2019 at 18:21
  • check this developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… Commented Sep 4, 2019 at 18:22
  • 1
    Possible duplicate of How to determine equality for two JavaScript objects? Commented Sep 4, 2019 at 18:24

1 Answer 1

2

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.
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.