Chapter XX · Classes

Private Fields

Private fields use a hash `#` prefix to enforce strict encapsulation, making properties inaccessible outside the class body.

01 How It Works

Think of a locked secure safety deposit box compartment hidden inside a vault.

Private class features are enforced at the engine syntax level, preventing external inspection or modification.

example.js
class BankAccount {
  #balance = 100;
  getBalance() { return this.#balance; }
}
const acc = new BankAccount();
// console.log(acc.#balance); // SyntaxError
  1. 1. Prefix class property or method identifiers with `#`.

  2. 2. Access or mutate private fields strictly within the class body.

  3. 3. Block external code access attempts.

02 Practical Example

Here is how you might see this concept applied in real-world code:

practical.js
class SecretHolder {
  #secret = "Hidden Value";
  reveal() { return this.#secret; }
}

Key Takeaway

Private fields (`#`) provide native data encapsulation and privacy for JavaScript classes.

Related Concepts