Simplified Class Definitions in JS: ES13

ECMAScript 2022 (ES13) made some nice updates to class definitions, making them easier to use.

This article focuses on two improvements: class field declarations and private methods and fields.

Class Field Declarations

Before ES13, defining class fields typically required using the constructor method. With class field declarations, you can define public and private fields directly in the class body outside any process.

Here's a class with some typical public fields declared using simple variable syntax:

class Person {
  name = "John Doe";
  age = 30;

  introduce() {
    console.log(`Hi, I'm ${this.name} and I'm ${this.age} years old.`);
  }
}

const person = new Person();
person.introduce(); // Output: Hi, I'm John Doe and I'm 30 years old.

In this example, name and age are public fields that can be accessed and modified from outside the class.

Private Fields

Private fields are declared using the # prefix:

class BankAccount {
  #balance = 0;

  deposit(amount) {
    this.#balance += amount;
  }

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

const account = new BankAccount();
account.deposit(100);
console.log(account.getBalance()); // Output: 100
// console.log(account.#balance); // This would throw an error

The #balance field is private and can only be accessed within the class methods.

Private Methods

ES13 also introduced private methods, which are defined using the # prefix:

class Calculator {
  #multiply(a, b) {
    return a * b;
  }

  square(n) {
    return this.#multiply(n, n);
  }
}

const calc = new Calculator();
console.log(calc.square(4)); // Output: 16
// console.log(calc.#multiply(2, 3)); // This would throw an error

The #multiply method is private and can only be called within the class.

I'm a big fan of these incremental improvements to JavaScript. Each one makes the language a little more readable and accessible to developers.

JavaScript
Avatar for Niall Maher

Written by Niall Maher

Founder of Codú - The web developer community! I've worked in nearly every corner of technology businesses: Lead Developer, Software Architect, Product Manager, CTO, and now happily a Founder.

Loading

Fetching comments

Hey! 👋

Got something to say?

or to leave a comment.