JavaScript Notes
Learn encapsulation in JavaScript with private class fields, getters, setters, closures, and real-world examples. Protect your data with ES2022 OOP techniques.
Encapsulation means bundling data (properties) and the methods that operate on that data together, while restricting direct access to the internal state. It prevents outside code from accidentally or maliciously corrupting an object's data.
Think of it as a capsule — the data is safely enclosed inside. You can only interact with it through the provided interface (methods), not directly.
📊 Encapsulation Diagram
💻 Example 1 — Private Fields with Getters and Setters
6300 Riya Account[Riya]: ₹6300
💻 Example 2 — Setter with Validation
class Temperature {
#celsius;
constructor(celsius) {
this.celsius = celsius; // ← triggers setter with validation
}
get celsius() { return this.#celsius; }
get fahrenheit() { return this.#celsius * 9/5 + 32; }
get kelvin() { return this.#celsius + 273.15; }
set celsius(value) {
if (value < -273.15) throw new Error("Below absolute zero!");
this.#celsius = value;
}
}
const temp = new Temperature(100);
console.log(temp.celsius); // getter
console.log(temp.fahrenheit); // computed getter
console.log(temp.kelvin); // computed getter
temp.celsius = 0;
console.log(temp.fahrenheit);
// temp.celsius = -300; // throws Error: Below absolute zero!100 212 373.15 32
💻 Example 3 — Encapsulation via Closures (Pre-ES2022)
1300
[ { type: 'deposit', amount: 500 }, { type: 'withdraw', amount: 200 } ]
undefined💻 Example 4 — Private Methods for Internal Logic
✅ Password saved for gmail true false
📋 Encapsulation Techniques Comparison
| Technique | Privacy Level | ES Version | Notes |
|---|---|---|---|
#privateField | True private | ES2022 | Best approach — enforced by engine |
_convention | Soft private | All | Just a naming convention — anyone can access |
| Closure | True private | All | No class needed — factory function pattern |
WeakMap | True private | ES6 | Stores private data outside the class |
Object.freeze() | Immutable | ES5 | Prevents adding/changing properties |
⚠️ Common Mistakes
❌ Mistake 1 — Using _ Underscore Is NOT True Privacy
class Account {
constructor(balance) {
this._balance = balance; // ← underscore is JUST a convention
}
}
const a = new Account(1000);
a._balance = -999999; // ← still works! No actual protection
console.log(a._balance);-999999
❌ Mistake 2 — Returning a Reference to Private Array
3
Fix: Return a copy:return [...this.#items]orreturn this.#items.slice()
❌ Mistake 3 — Forgetting Setter Means the Field Is Read-Only
class Config {
#apiKey = "abc123";
get apiKey() { return this.#apiKey; }
// No setter defined
}
const c = new Config();
c.apiKey = "newKey"; // silently ignored in non-strict, error in strict
console.log(c.apiKey); // still "abc123"abc123
🎯 Key Takeaways
- Encapsulation = bundle data + behavior and restrict direct access
- Use
#privateField(ES2022) for true privacy enforced by the JavaScript engine - Always provide getters for read access and setters with validation for write access
- Return copies of internal arrays/objects from public methods — never expose internal references
- Closures are a valid encapsulation pattern for factory functions without classes
- The
_underscoreconvention signals "internal" but provides zero actual protection - Encapsulation makes objects robust, predictable, and easier to maintain
❓ Interview Questions
Q1. What is encapsulation in JavaScript? > Encapsulation means bundling data (properties) with the methods that operate on that data inside an object, and restricting direct access to the internal state. Only controlled interfaces (public methods) can interact with private data.
Q2. How do you make a field truly private in JavaScript? > Use the # prefix — e.g., #balance = 0. This is a private class field enforced by the JavaScript engine (ES2022+). It is not accessible outside the class via any mechanism.
Q3. What is the difference between _name and #name? > _name is just a naming convention — the underscore signals "internal" but the field is still fully public. Anyone can read or write obj._name. #name is truly private — the engine blocks all outside access.
Q4. What are getters and setters used for in encapsulation? > Getters provide controlled read access to private data. Setters add validation logic before allowing writes. Together they create a safe interface: callers use obj.balance naturally, but the access goes through your validation code.
Q5. How did encapsulation work before private class fields? > Via closures in factory functions. Data declared in the outer function scope is naturally private to the returned object. For example, let balance = 0 inside a factory is accessible only through the returned deposit() and getBalance() methods.
Q6. Why is it bad to return a direct reference to a private array? > The caller gets a reference to the actual array, not a copy. Any mutation they do (push, splice, direct assignment) changes the private internal state, breaking encapsulation. Always return [...this.#array] or this.#array.slice().
Q7. Can you access private fields using JavaScript reflection or Proxy? > No. Private class fields (#) are a language-level feature — not properties on the object at all. Object.keys(), JSON.stringify(), Reflect, and Proxy cannot see them. Only the class body itself can access them.
Q8. What is the relationship between encapsulation and data integrity? > Encapsulation enforces data integrity by ensuring all mutations go through controlled methods. Instead of account.balance = -500 (invalid direct write), callers must use account.withdraw(500), which validates the amount and checks for sufficient funds first.
Exam Focus
Revise definitions, diagrams, examples, and short-answer points for Encapsulation in JavaScript – Private Fields, Getters, Setters & Data Protection.
Interview Use
Prepare one clear explanation, one practical example, and one common mistake for this JavaScript Master Course topic.
Search Terms
javascript-complete-guide, javascript master course, javascript, complete, guide, oop, encapsulation, encapsulation in javascript – private fields, getters, setters & data protection
Related JavaScript Master Course Topics