Private Fields Are Hard Private
You'll learn how private fields enforce true encapsulation, unlike the old convention-based approach.
The Convention vs. Reality Gap
For years, JavaScript developers used an underscore prefix (like _secret) to signal "please don't touch this." But it was just a gentleman's agreement—nothing actually stopped external code from accessing obj._secret directly.
Private fields with the # syntax change everything. They provide hard privacy: you literally cannot access a private field from outside the class. Not from subclasses, not from instances, not from clever workarounds. The engine enforces this at runtime.
What Makes Them "Hard Private"
class BankAccount {
#balance = 0;
deposit(amount) {
this.#balance += amount;
}
getBalance() {
return this.#balance;
}
}
const account = new BankAccount();
account.deposit(100);
console.log(account.getBalance()); // 100
console.log(account.#balance); // SyntaxError!
console.log(account['#balance']); // undefined (not a string property)
Unlike _balance, which could be accessed as account._balance or even account['_balance'], the #balance field is invisible outside the class body. There's no bracket notation trick, no Object.keys() workaround, no reflection magic. It's truly private.
Why This Matters
True encapsulation means you control all access paths. You can enforce invariants, validate inputs, and refactor internal implementations without worrying about external code reaching in and breaking your assumptions. The underscore convention relied on discipline; private fields enforce it structurally.
Key Takeaway: Private fields with # provide genuine encapsulation enforced by the JavaScript engine itself, not just a naming convention—external code has no way to access them, period.