🧭Encapsulation
Also known as Data Hiding, Information Hiding
Hiding an object's data. Other code must use safe methods to change it.
Think of it like
Think of it like a piggy bank. You can put coins in the slot, but you cannot reach in and grab them.
Example
Emma's Account class hides its balance. Other code must call deposit(), which says no to amounts below zero.
Why it matters
It stops other code from breaking an object by mistake.
Definition
Example code
javascript
class Account {
#balance = 0;
deposit(n) { this.#balance += n; }
get balance() { return this.#balance; }
}Common mistake
Key takeaways
- 1Data stays inside. Hidden from outside code.
- 2Safe doors only. Methods check each change.
- 3Free to change inside. Outside code does not break.