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

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.


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
a > b
a >= b
b < a
b > a

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

"[object Object]" < "[object Object]"
"[object Object]" > "[object Object]"
"[object Object]" >= "[object Object]"
"[object Object]" <= "[object Object]"

The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .
Read More:   Managing jQuery plugin dependency in webpack

Similar Posts