Private Fields in JavaScript
🧠 What Are Private Fields?
In JavaScript, private fields are properties that are accessible only within the class they are defined in. They are prefixed with a # symbol and provide true encapsulation by preventing external access.
Note
💡 Private fields cannot be accessed or modified from outside the class — not even by subclasses or reflection tools.
🔧 Syntax for Declaring Private Fields
Declaring Private Fields
class Person {
#name; // private field
constructor(name) {
this.#name = name;
}
getName() {
return this.#name;
}
}
const p = new Person("Alice");
console.log(p.getName()); // ✅ "Alice"
console.log(p.#name); // ❌ SyntaxErrorNote
⚠️ Accessing a private field outside the class using p.#name will throw a SyntaxError. Always use methods or getters to interact with them.
📌 Why Use Private Fields?
- 🔐 Enforce data hiding and encapsulation
- 📦 Avoid accidental modification of internal values
- 🧼 Create cleaner APIs by exposing only necessary methods
🧬 Private Fields vs Convention
Before private fields, developers used naming conventions like an underscore (e.g., _name) to indicate privacy. But this was only a suggestion — not enforced. With #name, it's enforced by the language.
| Approach | Enforced Privacy | Usage |
|---|---|---|
| _name (underscore) | ❌ No | Convention only |
| #name (private field) | ✅ Yes | Language-enforced |
🔍 Limitations of Private Fields
- Cannot be accessed or detected outside the class (even via reflection or Object.keys)
- Must be declared before use
- Only accessible within the class — not in subclasses
🔐 Encapsulation in Action
Let's look at a real-world example of encapsulation using private fields:
Encapsulation Example
class BankAccount {
#balance = 0;
deposit(amount) {
if (amount > 0) this.#balance += amount;
}
getBalance() {
return this.#balance;
}
}
const account = new BankAccount();
account.deposit(100);
console.log(account.getBalance()); // 100
console.log(account.#balance); // ❌ SyntaxError📚 Further Reading
>>“Encapsulation is not about hiding things from others. It’s about creating boundaries that protect your code.” 💬