Back to JavaScript
2026-01-155 min read

JavaScript classes.

Learn JavaScript classes. step by step with clear examples and exercises.

Why This Matters

JavaScript classes are a crucial part of modern JavaScript development. They offer a more object-oriented approach to writing code, making it easier to manage complex applications and maintain large codebases. By using classes, you can create reusable components that encapsulate data and behavior, leading to cleaner, more efficient code. Additionally, understanding classes is essential for working with popular JavaScript frameworks like React and Angular.

Prerequisites

Before diving into JavaScript classes, you should have a solid understanding of the following concepts:

  1. Variables and data types
  2. Functions
  3. Objects
  4. Prototypes
  5. ES6 syntax and features, such as arrow functions, template literals, and let/const declarations
  6. Understanding the call stack and event loop in JavaScript
  7. Familiarity with browser APIs and DOM manipulation

Core Concept

JavaScript classes provide a convenient syntax for creating objects that follow a specific structure or blueprint. They encapsulate data (properties) and behavior (methods) that operate on the data. Here's an example of a simple class:

class Rectangle {
constructor(height, width) {
this._height = height;
this._width = width;
}

get area() {
return this._height * this._width;
}
}

In this example, we've defined a Rectangle class with a constructor that takes in the height and width of the rectangle. The class includes an area property that calculates the area of the rectangle by returning the product of its height and width. To create an instance (object) of the Rectangle class, you can use:

const myRectangle = new Rectangle(5, 10);
console.log(myRectangle.area); // Outputs: 50

It's essential to note that JavaScript classes also support inheritance and prototypes, allowing you to create complex hierarchies of objects that share common properties and methods.

Worked Example

Let's create a more complex example with a Vehicle class that has properties for make, model, year, color, and numberOfDoors, as well as methods for accelerating, braking, calculating the vehicle's top speed, and determining whether it can fit in a parking space.

class Vehicle {
constructor(make, model, year, color, numberOfDoors) {
this._make = make;
this._model = model;
this._year = year;
this._color = color;
this._numberOfDoors = numberOfDoors;
}

accelerate() {
console.log(`Accelerating ${this._make} ${this._model}`);
}

brake() {
console.log(`Braking ${this._make} ${this._model}`);
}

topSpeed() {
// Calculate the top speed based on the vehicle type (e.g., car, truck)
return this._topSpeed;
}

canFitInParkingSpace(parkingSpaceWidth) {
const doorWidth = this._numberOfDoors * 2 + 4; // Assuming each door is 2 meters wide and there's a 4-meter space between doors
return parkingSpaceWidth > doorWidth;
}
}

class Car extends Vehicle {
constructor(make, model, year, color, numberOfDoors) {
super(make, model, year, color, numberOfDoors);
this._topSpeed = 200; // Example top speed for a car
}
}

const myCar = new Car("Toyota", "Corolla", 2021, "red", 4);
myCar.accelerate(); // Outputs: Accelerating Toyota Corolla
console.log(myCar.canFitInParkingSpace(25)); // Outputs: true

Common Mistakes

  1. Forgetting to call the constructor when creating an object:
const myCar = Car("Toyota", "Corolla", 2021, "red", 4); // Incorrect

Instead, use new:

const myCar = new Car("Toyota", "Corolla", 2021, "red", 4);
  1. Not using the this keyword correctly within methods:
class Rectangle {
constructor(height, width) {
this._height = height;
this._width = width;
}

area() {
return this.height * this.width; // Incorrect - using plain `height` and `width` instead of `this._height` and `this._width`
}
}
  1. Not understanding the difference between classes and objects:
  • Classes are templates for creating objects.
  • Objects are instances of a class, with their own properties and methods.
  1. Misusing static properties and methods (optional section):
  • Static properties and methods belong to the class itself rather than its instances.
  • They can be useful for defining shared functionality or constants that don't depend on instance data.
class Rectangle {
static PI = Math.PI; // Static property

constructor(height, width) {
this._height = height;
this._width = width;
}

area() {
return this._height * this._width * Rectangle.PI; // Using the static `PI` property
}
}
  1. Not understanding class inheritance and prototypes (optional section):
  • In JavaScript, classes can inherit from other classes using the extends keyword.
  • The parent class's prototype is automatically assigned to the child class's prototype, allowing for inheritance of properties and methods.
class Vehicle {
// ...
}

class Car extends Vehicle {
// ...
}

const carPrototype = Object.getPrototypeOf(new Car("Toyota", "Corolla", 2021, "red", 4));
console.log(carPrototype instanceof Vehicle); // Outputs: true

Practice Questions

  1. Create a Person class with properties for name, age, and occupation, as well as methods for introducing oneself and calculating the person's pension based on their age, salary, and years of service.
  2. Modify the Vehicle class from the worked example to include a method that calculates the vehicle's fuel consumption per 100 kilometers.
  3. Create a Shape class with a static method that calculates the total area of an array of shapes (assuming each shape has an area property).

FAQ

  1. Why use classes in JavaScript?
  • Classes offer a more object-oriented approach to writing code, making it easier to manage complex applications and maintain large codebases. They encapsulate data and behavior, leading to cleaner, more efficient code.
  • Classes also provide a convenient syntax for creating objects that follow a specific structure or blueprint.
  1. How are classes related to prototypes in JavaScript?
  • In JavaScript, classes are built on top of prototypes. Every object in JavaScript has a prototype, which is another object that stores properties and methods that can be inherited by other objects. When you create an instance of a class, it inherits from the class's prototype.
  1. Can I use classes with older versions of JavaScript (pre-ES6)?
  • No, classes were introduced in ES6 (2015). If you need to support older browsers, consider using a transpiler like Babel to convert your code to a format that older browsers can understand.
  1. What is the difference between a static property and an instance property?
  • Static properties belong to the class itself rather than its instances. They can be useful for defining shared functionality or constants that don't depend on instance data. Instance properties, on the other hand, are specific to each object created from the class.
  1. What is the difference between a static method and an instance method?
  • Static methods belong to the class itself rather than its instances. They can be called directly on the class without creating an instance. Instance methods, on the other hand, can only be called on objects created from the class.
JavaScript classes. | JavaScript | XQA Learn