Home » JavaScript Classes Tutorial with Examples

JavaScript Classes Tutorial with Examples

In JavaScript, classes are a way to define blueprints for creating objects. While JavaScript has been an object-oriented language from the start, ES6 (ECMAScript 2015) introduced the class keyword, which simplifies working with object-oriented programming (OOP) concepts such as inheritance, encapsulation, and polymorphism.

Though classes in JavaScript are syntactic sugar over prototypes, they provide a more intuitive and structured way to create and manage objects.

In this tutorial, you’ll learn:

What is a class in JavaScript?
Basic syntax of JavaScript classes
Creating and using class instances
Class constructors
Class methods (instance methods and static methods)
Inheritance in classes
Using super in derived classes
Practical examples of JavaScript classes

1. What is a Class in JavaScript?

A class in JavaScript is a blueprint for creating objects with shared properties and methods. Classes help you define objects more systematically, making it easier to create and reuse objects that share the same structure and behavior.

Before ES6, objects were created using constructor functions and prototypes. The class syntax simplifies this process.

2. Basic Syntax of JavaScript Classes

A JavaScript class is defined using the class keyword, followed by the class name, and a set of methods inside a block.

Syntax:

class ClassName {
    // Constructor
    constructor(parameters) {
        // Initialization
    }

    // Instance methods
    method1() {}
    method2() {}

    // Static methods
    static staticMethod() {}
}

3. Creating and Using Class Instances

You can create an instance of a class using the new keyword. Each instance of the class can have its own properties and methods.

Example 1: Basic Class and Instance

class Person {
    constructor(name, age) {
        this.name = name;
        this.age = age;
    }

    // Instance method
    greet() {
        console.log(`Hello, my name is ${this.name}, and I am ${this.age} years old.`);
    }
}

// Creating an instance of the Person class
const person1 = new Person('Alice', 30);

// Calling the instance method
person1.greet();  // Output: Hello, my name is Alice, and I am 30 years old.

In this example:

We define a class Person with a constructor to initialize name and age.
We create an instance person1 using new Person(), and we call the greet method to print the person's details.

4. Class Constructors

The constructor method is a special method in a class that gets called automatically when a new instance of the class is created. It’s used to initialize the object's properties.

Example 2: Constructor in a Class

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

    getCarInfo() {
        return `${this.brand} ${this.model}, ${this.year}`;
    }
}

const myCar = new Car('Toyota', 'Corolla', 2021);
console.log(myCar.getCarInfo());  // Output: Toyota Corolla, 2021

In this example:

The constructor takes brand, model, and year as parameters and initializes the instance's properties.
The getCarInfo method returns a string describing the car.

5. Class Methods (Instance Methods and Static Methods)

There are two types of methods in a JavaScript class:

Instance methods: These are methods that can be called on an instance of the class.
Static methods: These are methods that belong to the class itself and cannot be called on class instances.

Example 3: Instance Methods

Instance methods are defined without the static keyword. They are called on the instances of the class.

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

    // Instance method to calculate area
    getArea() {
        return this.width * this.height;
    }
}

const rect = new Rectangle(10, 20);
console.log(rect.getArea());  // Output: 200

In this example:

The getArea method is an instance method that calculates the area of the rectangle.

Example 4: Static Methods

Static methods are defined using the static keyword and are called on the class itself, not on an instance.

class MathUtil {
    // Static method to calculate the square of a number
    static square(x) {
        return x * x;
    }
}

console.log(MathUtil.square(5));  // Output: 25

In this example:

The square method is a static method that can be called on the MathUtil class itself. It cannot be called on an instance of the class.

6. Inheritance in Classes

Inheritance allows a class to extend another class, inheriting its properties and methods. The class that inherits is called the subclass or derived class, while the class being inherited from is called the superclass or base class.

Example 5: Class Inheritance

class Animal {
    constructor(name) {
        this.name = name;
    }

    speak() {
        console.log(`${this.name} makes a sound.`);
    }
}

// Dog is a subclass that inherits from Animal
class Dog extends Animal {
    constructor(name, breed) {
        super(name);  // Call the parent class constructor
        this.breed = breed;
    }

    speak() {
        console.log(`${this.name} the ${this.breed} barks.`);
    }
}

const dog = new Dog('Max', 'Golden Retriever');
dog.speak();  // Output: Max the Golden Retriever barks.

In this example:

The Dog class extends the Animal class and inherits the speak method.
The super(name) call invokes the constructor of the Animal class, initializing the name property.
The Dog class overrides the speak method with its own implementation.

7. Using super in Derived Classes

The super keyword is used to call the constructor or methods of a parent class in the subclass. It helps in reusing the parent class's logic.

Example 6: Using super to Call Parent Methods

class Employee {
    constructor(name, position) {
        this.name = name;
        this.position = position;
    }

    describe() {
        return `${this.name} works as a ${this.position}.`;
    }
}

class Manager extends Employee {
    constructor(name, position, department) {
        super(name, position);  // Call the parent class constructor
        this.department = department;
    }

    describe() {
        return `${super.describe()} They manage the ${this.department} department.`;
    }
}

const manager = new Manager('Alice', 'Manager', 'Sales');
console.log(manager.describe());
// Output: Alice works as a Manager. They manage the Sales department.

In this example:

The Manager class extends Employee and calls the parent constructor using super.
The describe method in Manager calls the parent’s describe method using super.describe() and then adds additional information.

8. Practical Examples of JavaScript Classes

Example 7: Shopping Cart System

Let’s implement a simple shopping cart using JavaScript classes.

class Product {
    constructor(name, price) {
        this.name = name;
        this.price = price;
    }

    getInfo() {
        return `${this.name} - $${this.price}`;
    }
}

class Cart {
    constructor() {
        this.items = [];
    }

    addItem(product) {
        this.items.push(product);
        console.log(`${product.name} added to the cart.`);
    }

    getTotalPrice() {
        return this.items.reduce((total, product) => total + product.price, 0);
    }

    checkout() {
        console.log("Checking out...");
        console.log(`Total: $${this.getTotalPrice()}`);
    }
}

const cart = new Cart();
const product1 = new Product("Laptop", 1000);
const product2 = new Product("Phone", 600);

cart.addItem(product1);  // Output: Laptop added to the cart.
cart.addItem(product2);  // Output: Phone added to the cart.
cart.checkout();         // Output: Total: $1600

In this example:

The Product class represents a product with a name and price.
The Cart class manages a list of items, allowing you to add products and calculate the total price.
The checkout method prints the total price of all items in the cart.

Conclusion

JavaScript classes provide a powerful way to implement object-oriented programming principles such as encapsulation, inheritance, and polymorphism. Here's a summary of what you've learned:

Classes are blueprints for creating objects with shared properties and methods.
Constructors are used to initialize new objects.
Instance methods are called on class instances, while static methods belong to the class itself.
Inheritance allows you to create new classes based on existing ones.
The super keyword is used to access the parent class's constructor and methods.

By understanding and using JavaScript classes effectively, you can write cleaner, reusable, and more maintainable code!

You may also like