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

  • 1
    Does this answer your question? [How to determine equality for two JavaScript objects?](https://stackoverflow.com/questions/201183/how-to-determine-equality-for-two-javascript-objects) – thedemons Nov 10 '22 at 00:27
  • 1
    @thedemons This question is about comparison with the help of `Symbol.toPrimitive`. – gre_gor Nov 10 '22 at 00:42

1 Answers1

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
Benjamin Penney
  • 637
  • 3
  • 10