Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);
}
like image 541
Stephan Ahlf Avatar asked Jan 01 '23 03:01

Stephan Ahlf


1 Answers

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.

like image 77
sdgfsdh Avatar answered Jan 05 '23 18:01

sdgfsdh