Stephan Ahlf
Stephan Ahlf

Reputation: 3497

Is it possible to implement equal operator in ES6?

Is it possible to implement equal operator in ES6?

Instead of implementing an equals() method in class it would be nice to use if (myClassObject1 === myClassObject2) {}

Can we implement custom math operators in es6 javascript classes?

In c# it is possible to override it as follows

public static bool operator ==(Complex x, Complex y)
{
   return x.re == y.re && x.im == y.im;
}

public static bool operator !=(Complex x, Complex y)
{
   return !(x == y);
}

Upvotes: 6

Views: 1180

Answers (1)

sdgfsdh
sdgfsdh

Reputation: 37045

No, you cannot do this.

The == and === operators are explained here, and they cannot be changed by the programmer.

A typical work-around is define an "equality" function and use that. For example, using the one from lodash:

const a = { name: 'Alireza' };
const b = { name: 'Alireza' };

_.isEqual(a, b); // true

Brendan Eich discusses adding "Value Objects" here.

Upvotes: 9

Related Questions