Encapsulation
In one line
Encapsulation is the practice of bundling data and the methods that operate on it together, while hiding internal details.
In simple words
Encapsulation means putting data and the functions that work on that data into one unit (like a class or object), and hiding the internal details from the outside. The outside world can only interact through a controlled interface (public methods).
Think of a car: you use the steering wheel and pedals (the interface), but you do not need to know how the engine works internally (the encapsulated details). If the manufacturer changes the engine, you still steer the same way.
Encapsulation benefits: (1) it simplifies usage — you use the interface without understanding internals, (2) it protects data — internal state cannot be corrupted by external code, (3) it enables change — you can rewrite internals without breaking callers. In JavaScript, closures and private fields (#field) provide encapsulation.
Example
class BankAccount {
#balance = 0; // private field
deposit(amount) {
if (amount > 0) this.#balance += amount;
}
getBalance() {
return this.#balance;
}
}
const account = new BankAccount();
account.deposit(100);
console.log(account.getBalance()); // 100
// account.#balance = 999; // Error — cannot access private fieldThe #balance field is private — it can only be modified through the deposit method. External code cannot directly set or read it, protecting the data from invalid states.
Related terms
Related Resources
Related Lessons
- Programming Paradigms
Learn about OOP concepts.
Decode error messages
Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.