JavaScript private fields, getters, and static members

A field whose name starts with # is private: only code inside the class body can read or write it. Outside code that tries to access it gets a syntax error, and the field does not appear in Object.keys or JSON.stringify. This is real encapsulation, unlike the old convention of a leading underscore.

JavaScript
class Account {
  #balance = 0;
  static count = 0;

  constructor(owner) {
    this.owner = owner;
    Account.count++;
  }

  deposit(amount) {
    if (amount <= 0) {
      throw new RangeError("amount must be positive");
    }
    this.#balance += amount;
    return this;
  }

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

const account = new Account("Ada");
account.deposit(50).deposit(25);
console.log(account.balance, Account.count);

try {
  account.deposit(-1);
} catch (error) {
  console.log(error.name + ": " + error.message);
}

console.log(Object.keys(account).join(","));
console.log(JSON.stringify(account));
Read the full lesson