Search code examples
javascriptequalitycomparison-operators

Can you override what == does in Javascript?


In Python, it's possible to override what == does by defining a __eq__ method for your class.

Is it possible to do something similar in Javascript? If so, how do you do it?

My understanding is that, by default (and maybe always, if you can't override it), Javascript just checks to see if two objects reside at the same address when you do a ==. How can I get the address directly?

I'm asking all of this because I'm trying to debug some code someone who's long gone wrote. As far as I can tell, two objects are identical, and yet == is returning false. I'm trying to find why... I'm wondering if maybe == was overridden someplace (but it's a big codebase and I don't know what to search for) or if or if maybe the object was duplicated, so they exist at different addresses despite being identical as far as I can tell. Knowing how to get the address would help with confirming that theory and give me a lead to hunt down the problem.


Solution

  • Not typically. JS does not allow operator overloading or operators-as-methods.

    There are certain operators that call toString or valueOf internally, which you can override on your own classes, thus influencing the behavior.