How do you make a property private in JavaScript classes?
Prefix the field with
Explain it simply
An older habit was to write _balance and ask people not to touch it. Modern JavaScript has real private fields: #balance. Outside the class, even reading wallet.#balance is a syntax error, not just a bad idea.
Combine private fields with getters and methods to expose only what the outside world should see.
Example
class Wallet {
#balance = 0;
deposit(n) {
if (n <= 0) throw new Error("amount must be positive");
this.#balance += n;
}
get balance() { return this.#balance; }
}
const w = new Wallet();
w.deposit(100);
w.deposit(50);
console.log(w.balance); // Output: 150
console.log(Object.keys(w).length); // Output: 0
console.log(JSON.stringify(w)); // Output: {}Private methods work the same way: #validate() { ... }.
What to say in the interview
"I use #name for private fields, which the language enforces. They are invisible to reflection-style tools such as Object.keys, so the only way in is through the class's own methods and getters. The underscore style is only a convention."
Common mistakes
- Using _name and assuming it is private. Anyone can still read and change it.