JavaScriptMedium
What are Private Fields?
Private fields and methods are class members whose names start with # (#balance, #validate()); they can only be accessed from inside the class body, and the language enforces this, unlike the old _underscore convention.
What can be private
- Instance fields:
#count = 0. - Instance methods:
#validate() {}. - Getters/setters:
get #total() {}. - Static fields and methods:
static #instances = 0.
How they behave
- Truly inaccessible from outside:
obj.#fieldoutside the class is a syntax error, and they do not appear inObject.keys,JSON.stringify,for...inor evenReflect.ownKeys. - Per-class, not per-object: any instance method can read
#fieldon another instance of the same class (useful forequalsmethods). - Brand checks:
#field in objreturns whetherobjwas created by this class, a reliable alternative toinstanceofacross realms. - Not inherited for access: subclasses cannot read the parent's private fields directly; expose protected behaviour through methods.
- Accessing a private field on an object that does not have it throws a
TypeError.
Why use them
- Protect invariants (a bank balance changes only through
deposit/withdraw). - Hide implementation details so you can change them without breaking users.
- Avoid name clashes with subclass fields.
Trade-offs
Proxies and some libraries cannot intercept private fields, and they cannot be accessed for debugging in code (DevTools still shows them). For object-literal-style code, closures provide the same privacy.
Code example
js
1class BankAccount {2 #balance = 0;3 #history = [];4 static #accounts = 0;56 constructor(owner) {7 this.owner = owner;8 BankAccount.#accounts++;9 }1011 #record(type, amount) {12 this.#history.push({ type, amount });13 }1415 deposit(amount) {16 if (amount <= 0) throw new RangeError("Amount must be positive");17 this.#balance += amount;18 this.#record("deposit", amount);19 return this;20 }2122 withdraw(amount) {23 if (amount > this.#balance) throw new Error("Insufficient funds");24 this.#balance -= amount;25 this.#record("withdraw", amount);26 return this;27 }2829 get balance() {30 return this.#balance;31 }3233 static isAccount(obj) {34 return #balance in obj; // brand check35 }3637 static get count() {38 return BankAccount.#accounts;39 }40}4142const acc = new BankAccount("Ada").deposit(100).withdraw(30);43console.log(acc.balance, acc.owner); // 70 Ada44console.log(Object.keys(acc), JSON.stringify(acc)); // ["owner"] {"owner":"Ada"}45console.log(acc["#balance"]); // undefined - not a normal property46console.log(BankAccount.isAccount(acc), BankAccount.isAccount({ balance: 70 })); // true false4748try {49 acc.withdraw(1000);50} catch (e) {51 console.log(e.message); // Insufficient funds52}53console.log(BankAccount.count); // 1
Practice this question
Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the JavaScript set.