A class in JavaScript is a blueprint for creating objects that share the same structure and behavior. If you've ever created several similar objects by hand — a few users, a few products — a class lets you define that shape once and stamp out as many instances as you need.

Classes were added to JavaScript in ES6 (2015). Under the hood they still use JavaScript's existing prototype system, but the class syntax reads much closer to how other object-oriented languages look, which makes it easier to write and easier to read.

Defining a Class

class Car {
  constructor(brand, year) {
    this.brand = brand;
    this.year = year;
  }

  describe() {
    return `${this.brand} (${this.year})`;
  }
}

const car1 = new Car("Toyota", 2022);
const car2 = new Car("Honda", 2024);

console.log(car1.describe());
console.log(car2.describe());

Output:

Toyota (2022)
Honda (2024)

The constructor method runs automatically every time you create a new instance with new. It's where you set up each object's starting properties using this, which refers to the specific instance being created.

Instance Methods

Any function defined inside the class body (other than the constructor) becomes a method every instance can call. Methods are shared across all instances rather than duplicated on each one, which is more memory-efficient than attaching a separate copy of the function to every object.

class Counter {
  constructor() {
    this.count = 0;
  }

  increment() {
    this.count++;
  }
}

const c = new Counter();
c.increment();
c.increment();
console.log(c.count);

Output:

2

Classes vs the Old Function Pattern

Before ES6, developers achieved the same thing with a constructor function and manually attaching methods to its prototype:

// Pre-ES6 equivalent of the Counter class above
function Counter() {
  this.count = 0;
}
Counter.prototype.increment = function () {
  this.count++;
};

Both versions do exactly the same thing — class is syntax sugar on top of JavaScript's existing prototype-based inheritance, not a completely new mechanism. Once you're comfortable creating a basic class, the natural next step is making one class build on another with inheritance using extends and super.