Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to perform less than/greater than comparisons on custom objects in javascript

Tags:

I have a custom class that has several members. I need to compare them to each other. javascript lets me write:

var a = new MyType(1); var b = new MyType(2); if (a < b) { ... 

but I don't understand the behavior of the logical comparison. Can someone explain the semantics of the < comparison in the above code? Is there a way to control what happens so that I can get right behavior? I know I can write a comparison method for the class, but since javascript lets me write it, I wondered what it thought it was doing.

Thanks.

like image 291
drdwilcox Avatar asked Apr 26 '12 18:04

drdwilcox


People also ask

What is the best way to compare objects in JavaScript?

Comparing objects is easy, use === or Object.is(). This function returns true if they have the same reference and false if they do not. Again, let me stress, it is comparing the references to the objects, not the keys and values of the objects. So, from Example 3, Object.is(obj1,obj2); would return false.

How can we compare two objects in JavaScript?

Objects are not like arrays or strings. So simply comparing by using "===" or "==" is not possible. Here to compare we have to first stringify the object and then using equality operators it is possible to compare the objects.

How do you compare values in objects?

Referential equality JavaScript provides 3 ways to compare values: The strict equality operator === The loose equality operator == Object.is() function.

How do you compare variables in JavaScript?

= is used for assigning values to a variable in JavaScript. == is used for comparison between two variables irrespective of the datatype of variable. === is used for comparision between two variables but this will check strict type, which means it will check datatype and compare two values.


1 Answers

You need to define a .valueOf method that returns a primitive that can be used for comparison:

function MyType( value ){     this.value = value; }  MyType.prototype.valueOf = function() {     return this.value; };  var a = new MyType(3),     b = new MyType(5);  a < b true a > b false a >= b false b < a false b > a true 

If you don't define it, the the string "[object Object]" is used for comparison:

"[object Object]" < "[object Object]" false "[object Object]" > "[object Object]" false "[object Object]" >= "[object Object]" true "[object Object]" <= "[object Object]" true 
like image 150
Esailija Avatar answered Oct 12 '22 14:10

Esailija