Interview Q&A / Object-Oriented Programming

IntermediateQuick answer1 min readUpdated 3 Oct 2026

How do you make a property private in JavaScript classes?

SHORT ANSWER

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

js
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.

#javascript#encapsulation#classes

Related questions

Practise more Object-Oriented Programming questions

Test your recall with short answers, then return to the detailed explanations when you need context.

Open Object-Oriented Programming quick answers →

Get new questions like this by email

One short email when something new and useful lands. No spam, unsubscribe in one tap.

By subscribing you agree to the Privacy Policy.