Operator overloading for non-value objects

Brendan Eich brendan at mozilla.com
Mon Jan 13 12:49:57 PST 2014


Thanks for the reply.

Domenic Denicola wrote:
> In JavaScript, our data structures are specified to use SameValue (or SameValueZero, or Strict Equality Comparison); none of them use a user-overridable hook. Furthermore, years of best-practice advice have made a lot of programmers prefer using `===` exclusively, ignoring `==` altogether. I for one would find it uncomfortable to start switching to `==` on the hope that it does something useful, in case the left-hand side is a value object with a proper overload implementation. (I would of course want to*avoid*  it for the primitives, since its coercion behavior there is rarely desired.)

Indeed, writing something like

   if (urlObj == "http://foo.com") {...}

today could take advantage of toString or valueOf to "overload".

> So ... I guess I am saying, I am not sure that making `==` work for mutable objects is salvagable. It can be made to work for immutable objects, maybe,

definitely

>   assuming that their immutability is also used to modify SameValue et al. and thus allow a consistent behavior between `==` and e.g. `map.has`.

No, that's ===. For value objects, == is completely overloadable.

Of course, a buggy or perverse implementation could give inconsistent 
results, so my argument against mutability is weaker and relies on best 
effort/testing. So I'm not totally, unalterably opposed, but I am opposed.

Your point about it being too late to salvage == (vs. ===) is good, but 
perhaps with value objects plus further work to disable implicit 
conversions, == will make a come-back -- but that's far down the road.

>   (I suppose I am asking for invariants `x == y&&  Type(x) is Object&&  Type(y) is Object` implies `map.has(x) === map.has(y)`.)

That follows from the x == y && typeof x == typeof y <=>  x === y 
relation already in the language, except for NaNs (which you ignored, so 
I will too!).

>   But unless we are prepared to allow the overloaded `==` to propagate throughout the language, which seems unlikely since the language rarely uses Abstract Equality Comparison, then I can't really see a place for `==` overloading on mutable objects.

Good argument, thanks for making it.

/be


More information about the es-discuss mailing list