Logo

JavaScript Classes: A Beginner's Guide

A comprehensive guide to understanding and implementing JavaScript Classes for object-oriented programming

Salman Khan

5/10/2025 · 2 min read

JavaScript Classes

In JavaScript, classes let you define blueprints for creating objects. A class groups related data (properties) and functionality (methods). Think of a class as a template for creating objects.

What is a Class?

A class is a special type of function in JavaScript that helps you organize and reuse code. You use it to define the structure of an object—what properties it has and what methods it can run.

For example, a Car class might define that every car has a make, a model, and a method to display its details.

Declaring a Class

You declare a class using the class keyword:

class Car {
  // Class body goes here
}

By convention, class names start with a capital letter.

Constructor: Setting Up New Objects

The constructor() is a special method that runs when you create a new instance of a class.

class Car {
  constructor(make, model) {
    this.make = make;
    this.model = model;
  }
}

What’s happening here:

  • constructor(make, model) is a function that takes two arguments.
  • this.make = make; assigns the make value to the object.
  • this.model = model; does the same for model.

Adding Methods

You can add methods directly inside the class, just like functions:

class Car {
  constructor(make, model) {
    this.make = make;
    this.model = model;
  }

  displayInfo() {
    console.log(`This car is a ${this.make} ${this.model}.`);
  }
}

Creating and Using Instances

Now let’s use the Car class:

const myCar = new Car("Toyota", "Corolla");

console.log(myCar.make); // Output: Toyota
myCar.displayInfo(); // Output: This car is a Toyota Corolla.

Explanation:

  • new Car(...) creates a new object from the class.
  • You can access properties using myCar.make.
  • Call methods like myCar.displayInfo().

Inheritance with extends

Inheritance lets one class reuse the logic of another class using the extends keyword.

class ElectricCar extends Car {
  constructor(make, model, batteryCapacity) {
    super(make, model); // Calls the parent (Car) constructor
    this.batteryCapacity = batteryCapacity;
  }

  displayBatteryInfo() {
    console.log(`Battery capacity: ${this.batteryCapacity} kWh.`);
  }
}

Using super()

When using inheritance, the super() function calls the parent class’s constructor.

const tesla = new ElectricCar("Tesla", "Model S", 100);

tesla.displayInfo(); // Inherited method
tesla.displayBatteryInfo(); // Own method

Summary

ConceptWhat It Does
classDeclares a new class
constructorSets up new object properties
thisRefers to the current object
newCreates a new object instance
MethodFunction inside a class
extendsInherit from another class
super()Calls the parent class’s constructor