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

SurveyJS custom survey software

JavaScript UI Libraries for Surveys and Forms

SurveyJS lets you build a JSON-based form management system that integrates with any backend, giving you full control over your data and no user limits. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more.

Learn more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs