Tutorials

An Introduction to ES6 Classes

The ES6 class brought a welcomed makeover to JavaScript's object-oriented programming model, hiding the quirks of prototyping behind a more familiar and intuitive syntax. Whether you're used to other languages or fresh to classes, ES6 makes it simpler to define clear structures for your code.

Let's refresh your understanding of ES6 classes by defining their construction, properties, methods, inheritance, and how the landscape has evolved with private methods in ECMAScript 2026.

Key Takeaways

  • ES6 classes simplify prototyping by introducing the class keyword for defining objects.
  • The constructor method initializes class instances with specific properties.
  • Classes can be extended for inheritance, enabling more organized and reusable code.
  • Private methods are now supported directly in JavaScript, no longer just in TypeScript or other languages.

JavaScript ES6 Classes

With the class keyword, ES6 wraps the complexity of prototyping into a more familiar concept. You can now define a class without touching function or prototype. Here's a simple example of what a class looks like in JavaScript:

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

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

const dog = new Animal('Charlie', 'Dog');
dog.speak(); // Charlie makes a noise.

JavaScript Class Constructor

The constructor is where you set up your new object with default values or dynamic initialization logic. Here's an updated Person class:

class Person {
    constructor(first, last) {
        this.first = first;
        this.last = last;
    }

    greet() {
        return `Hello, ${this.first} ${this.last}!`;
    }
}

let user = new Person('John', 'Doe');
console.log(user.greet()); // Hello, John Doe!

ES6 Class Properties

Class properties in ES6 are initialized using the constructor, sometimes alongside method definitions. Here's a straightforward example:

In defining the Person class above, initializing properties is done in the constructor function, assigning first and last to the class. Properties can be accessed and manipulated using methods or directly if not private.

ES6 Class Methods

Class methods in ES6, like any function, define behaviors for your objects. Adding a method to print the full name is as easy as:

class Person {
    constructor(first, last) {
        this.first = first;
        this.last = last;
    }

    getFullName() {
        return `${this.first} ${this.last}`;
    }
}

let person = new Person('Alice', 'Smith');
console.log(person.getFullName()); // Alice Smith

ES6 Class Inheritance: Extending Classes

Inheritance in ES6 is handled through the extends keyword, enabling subclasses to access and override properties and methods from a parent class. Here's a subclass example:

class FormalPerson extends Person {
    constructor(first, last, title) {
        super(first, last);
        this.title = title;
    }

    getFormalName() {
        return `${this.title} ${this.first} ${this.last}`;
    }
}

const formalPerson = new FormalPerson('Alan', 'Turing', 'Dr.');
console.log(formalPerson.getFormalName()); // Dr. Alan Turing

ES6 Class Private Methods

Contrary to the early limitations in ES6, private methods are now supported through the use of a # prefix. This feature offers a significant upgrade compared to previous workarounds, allowing you to encapsulate behavior more effectively:

class SecureDocument {
    #validate() {
        // Private logic
        return true;
    }

    process() {
        if (this.#validate()) {
            console.log('Document is valid');
        }
    }
}

const doc = new SecureDocument();
doc.process(); // Document is valid
// doc.#validate(); // SyntaxError: Private field '#validate' must be declared in an enclosing class

FAQ

What are the main benefits of using ES6 classes?

ES6 classes offer a cleaner, more declarative syntax which simplifies prototyping. They ensure more readable and maintainable code by mimicking traditional class-based object-oriented programming languages.

How do you declare a private field in an ES6 class?

You declare a private field using a # before the field name. This makes the field inaccessible outside the defining class, providing encapsulation.

Why use inheritance in classes?

Inheritance allows for extending existing functionality, promoting code reusability, and simplifying maintenance by organizing related classes logically.

Is it necessary to use TypeScript for private methods?

No, it's no longer necessary. As of recent ECMAScript standards, you can use the # syntax to declare private methods directly in JavaScript classes.

Mastering the tech interviewWhat everyone is doing wrong in tech interviews