JavaScript classes provide a structured way to create objects and organize related data and methods. A class acts as a blueprint for creating objects with similar properties and behaviors.

JavaScript introduced class syntax in ECMAScript 2015 (ES6). Although classes provide a cleaner syntax for object-oriented programming, JavaScript classes are built on top of its prototype-based inheritance system.

JavaScript Class Syntax

You can define a class using the class keyword, followed by its name and a pair of curly braces.

class Person {
    // Properties and methods
}

By convention, class names use PascalCase, meaning the first letter of each word is capitalized.

Creating a JavaScript Class

The following example demonstrates how to create a simple JavaScript class.

class Person {
    greet() {
        console.log("Hello, JavaScript!");
    }
}

const person1 = new Person();

person1.greet();

Output:

Hello, JavaScript!

In this example:

  • class Person declares a class named Person.
  • greet() defines a method inside the class.
  • new Person() creates an object from the class.
  • person1.greet() calls the method.

An object created from a class is called an instance of that class.

JavaScript Class Constructor

A constructor is a special method used to initialize an object when it is created. A class can have only one constructor method.

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

    displayInfo() {
        console.log(`Name: ${this.name}`);
        console.log(`Age: ${this.age}`);
    }
}

const person1 = new Person("John", 25);

person1.displayInfo();

Output:

Name: John
Age: 25

The constructor() method runs automatically when you create an object using the new keyword.

The this keyword refers to the current instance. In this example, it assigns the supplied values to the object’s name and age properties.

JavaScript Class Methods

Methods are functions defined inside a class. They describe the actions that objects created from the class can perform.

class Calculator {
    add(a, b) {
        return a + b;
    }

    multiply(a, b) {
        return a * b;
    }
}

const calculator = new Calculator();

console.log(calculator.add(10, 5));
console.log(calculator.multiply(10, 5));

Output:

15
50

You can call an instance method using the object name followed by the method name.

JavaScript Class Properties

Properties store data associated with a class instance. You can initialize instance properties inside the constructor.

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

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

console.log(car1.brand);
console.log(car1.model);

Output:

Toyota
Corolla

Each instance can have its own property values.

JavaScript Static Methods

Static methods belong to the class itself rather than individual instances. You can define them using the static keyword.

class MathHelper {
    static square(number) {
        return number * number;
    }
}

console.log(MathHelper.square(5));

Output:

25

You call a static method using the class name. It cannot be called directly through an instance in the same way as an ordinary instance method.

JavaScript Class Inheritance

JavaScript supports inheritance using the extends keyword. A child class can inherit properties and methods from a parent class.

class Animal {
    eat() {
        console.log("This animal eats food.");
    }
}

class Dog extends Animal {
    bark() {
        console.log("The dog barks.");
    }
}

const dog1 = new Dog();

dog1.eat();
dog1.bark();

Output:

This animal eats food.
The dog barks.

The Dog class inherits the eat() method from Animal and defines its own bark() method.

JavaScript Class and the super Keyword

The super keyword is used to call a parent class constructor or access parent class methods from a child class.

When a child class defines a constructor, it must call super() before accessing this.

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

class Student extends Person {
    constructor(name, grade) {
        super(name);
        this.grade = grade;
    }

    display() {
        console.log(`${this.name} is in grade ${this.grade}.`);
    }
}

const student1 = new Student("Sarah", 10);

student1.display();

Output:

Sarah is in grade 10.

Here, super(name) calls the parent class constructor and initializes the inherited name property.

JavaScript Getters and Setters in Classes

Getters and setters allow you to define methods that are accessed like properties. A getter retrieves a value, while a setter updates it.

class User {
    constructor(name) {
        this._name = name;
    }

    get name() {
        return this._name;
    }

    set name(newName) {
        this._name = newName;
    }
}

const user1 = new User("John");

console.log(user1.name);

user1.name = "David";

console.log(user1.name);

Output:

John
David

The get keyword defines a getter, and the set keyword defines a setter.

JavaScript Private Class Fields

JavaScript supports private class fields using the # prefix. Private fields can only be accessed from within the class body.

class BankAccount {
    #balance = 1000;

    getBalance() {
        return this.#balance;
    }
}

const account = new BankAccount();

console.log(account.getBalance());

Output:

1000

Trying to access account.#balance from outside the class causes a syntax error because the field is private.

JavaScript Class Expressions

You can also create a class using a class expression and assign it to a variable.

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

    greet() {
        console.log(`Hello, ${this.name}!`);
    }
};

const person1 = new Person("Alice");

person1.greet();

Output:

Hello, Alice!

Unlike a class declaration, a class expression can be anonymous or have an internal name.

JavaScript Class vs Constructor Function

Before ES6 class syntax was introduced, constructor functions were commonly used to create objects with shared methods.

JavaScript Class Constructor Function
Uses the class keyword. Uses a regular function.
Uses the constructor() method. Uses function parameters and this.
Methods are defined inside the class body. Methods can be added to the prototype.
Supports extends and super. Uses prototype-based inheritance manually.
Cannot be called without new. Can be called like a regular function, depending on its definition.

Both approaches use JavaScript’s prototype system to support object behavior and inheritance.

Categorized in:

JS Basic, Javascript,