DEV Community

Avraam Mavridis
Avraam Mavridis

Posted on

4 3

CodeTip - Javascript: Compare class instances

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

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read full post →

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more