For example, in Javascript [1,2,3] === [1,2,3]
and [1,2,3] == [1,2,3]
are both false. Even the simpler case of the empty array is also false. The reason being that arrays are reference types and [1,2,3]
and [1,2,3]
are different as references. Javascript is not unique in this regard and pretty much every language implements equality as being reference equality except for the most basic types like integers and maybe some built-in types.
Why is this the case? What's so hard about making the default equality operator something stronger? So instead of just comparing references why is it so hard to compare structural properties as well?
I know that many languages provide facilities for overloading certain operators to mean something else so that ==
will mean what you want it to mean instead of the usual weak reference equality. My question is not whether the language provides such facilities but why the default equality operator isn't something more sensible so that [1,2,3] == [1,2,3]
evaluates to true by default and requires no programmer intervention.
In python the above example evaluates to true but if you define the following class
class A:
def __init__(self, prop):
self.prop = prop
and then compare a = A(1)
to b = A(1)
then the answer will be false even though structurally a
and b
are the same and there is no way to tell them apart if all you know is the bit pattern that defines the object.