private class fields

ES2022, JavaScript, Classes

Create truly private properties and methods in JavaScript classes using the # syntax.

Explanation

  • #propertyName: Creates a private field that cannot be accessed from outside the class.
  • #methodName(): Creates a private method only accessible within the class.
  • Private fields must be declared in the class body before use.
  • Attempting to access private fields from outside throws a SyntaxError.

Usage

To create classes with private fields and methods:

class BankAccount {
  #balance = 0;
  #accountNumber;

  constructor(initialBalance, accountNumber) {
    this.#balance = initialBalance;
    this.#accountNumber = accountNumber;
  }

  #validateAmount(amount) {
    return amount > 0 && typeof amount === 'number';
  }

  deposit(amount) {
    if (this.#validateAmount(amount)) {
      this.#balance += amount;
      return this.#balance;
    }
    throw new Error('Invalid amount');
  }

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

const account = new BankAccount(100, '12345');
console.log(account.getBalance()); // 100
// console.log(account.#balance); // SyntaxError: Private field '#balance' must be declared in an enclosing class