DEV Community

loading...

CodeTip - Javascript: Compare class instances

Avraam Mavridis
・1 min read

Many times we are in situations we want to compare instances of a class, aka objects, for example in case you develop a game and you want to compare instances of a gameobject, e.g. Car:

class Car {
  constructor(speed){
    this.speed = speed
  }
}

Let's say we want to compare instances of a car (or sort/filter an array of them). Obviously we can do:

const car1 = new Car(100)
const car2 = new Car(120)
const car3 = new Car(90)

console.log(car2.speed > car1.speed) // true

const sorted = [car1, car2, car3].sort((a,b) => {
  return a.speed - b.speed;
});

This works perfectly fine but we can do better, so we don’t have to type .speed every time we want to compare two cars, or sort/filter an array of them. We can define a valueOf method in the Car class, the method returns the “value” of the instance.

class Car {
  constructor(speed){
    this.speed = speed
  }

  valueOf(){
    return this.speed;
  }
}


const car1 = new Car(100)
const car2 = new Car(120)
const car3 = new Car(90)

console.log(car2 > car1) // true

Discussion (1)

Forem Open with the Forem app