2

I am trying to compare 2 different javascript objects by the default value. if both objects are bearing same value then it shall return true please see the code below.

let user1 = {
  name: "John",

  [Symbol.toPrimitive]() {
    return this.name;
  }
};

let user2 = {
  name: "John",

  [Symbol.toPrimitive]() {
    return this.name;
  }
};

console.log(user1 == user2); //expecting 'John' == 'John' and so true

if I use

(user1.toString() == user2.toString()) //true
(user1 == user2.toString()) //true
(user1.toString() == user2) //true
(user1 == user2) //false

But what I would like to see if

(user1 == user2) //expecting true but currently its giving false

2

1 Answer 1

3

Despite the == operator being coercive, there is no type coercion being performed when you compare the two values in this case. They are both objects, so no conversion is necessary. One pattern you can use is to compare values inside the objects in a .equals method. If you want to use [Symbol.toPrimitive], you could first coerce them both to strings:

"" + user1 === "" + user2
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.