SyntaxStudy
Sign Up
JavaScript Private Class Fields and Methods
JavaScript Advanced 8 min read

Private Class Fields and Methods

Private Class Fields and Methods

JavaScript's class field syntax, now widely supported, includes true private fields using the # prefix. Private fields can only be accessed inside the class body — not from subclasses, not from external code — providing genuine encapsulation rather than just convention-based privacy.

Private Fields

Declare a private field at the top of the class body with #fieldName;. Access and modify it anywhere inside the class with this.#fieldName. Any attempt to access it from outside throws a SyntaxError.

Private Methods

Prefix a method with # to make it private. Private methods can only be called from within the class. They are ideal for internal helper logic that should not be part of the public API.

in Operator for Private Fields

Use #field in obj to check if an object has a specific private field — useful for type-checking inside static methods.

Example
class BankAccount {
  #balance;
  #owner;
  #transactions = [];
  constructor(owner, initialBalance) {
    this.#owner = owner;
    this.#balance = initialBalance;
  }
  #recordTransaction(type, amount) {
    this.#transactions.push({ type, amount, date: new Date() });
  }
  deposit(amount) {
    if (amount <= 0) throw new Error('Invalid amount');
    this.#balance += amount;
    this.#recordTransaction('deposit', amount);
  }
  get balance() { return this.#balance; }
  get owner() { return this.#owner; }
}
const acc = new BankAccount('Alice', 1000);
acc.deposit(500);
console.log(acc.balance); // 1500
// console.log(acc.#balance); // SyntaxError
Pro Tip

Private fields enforce encapsulation at the language level — unlike the old underscore convention (_field), which is just a gentleman's agreement, #field truly cannot be accessed from outside the class even in the same file.