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);
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With