What Encapsulation Means in JavaScript
You'll learn: What encapsulation is in JavaScript and how it helps you control access to an object's internal state.
The Core Idea
Encapsulation is the practice of bundling data (properties) and behavior (methods) together while controlling what the outside world can see and modify. In traditional object-oriented programming, you'd use keywords like private and public. JavaScript doesn't enforce access restrictions automatically — it's a loosely-typed language with no built-in "hard" privacy — so encapsulation becomes more of a design principle than a language rule.
The goal? Hide implementation details and expose only what's necessary. This prevents accidental misuse, makes refactoring safer, and creates clearer boundaries between different parts of your code.
How JavaScript Approaches Encapsulation
Since JavaScript won't stop you from accessing any property (everything is technically "public"), you achieve encapsulation through:
- Convention: Prefixing properties with
_to signal "don't touch this directly" - Closures: Keeping variables inside factory functions so they're truly inaccessible
- Private fields (modern): Using
#syntax in classes (ES2022) - Controlled interfaces: Only exposing specific methods/getters/setters
// Factory with closure-based encapsulation
function createBankAccount(initialBalance) {
let balance = initialBalance; // truly private
return {
deposit(amount) {
balance += amount;
},
getBalance() {
return balance;
}
};
}
const account = createBankAccount(100);
account.deposit(50);
console.log(account.getBalance()); // 150
console.log(account.balance); // undefined — can't access directly!
The outside world interacts through deposit() and getBalance(), but balance itself remains hidden. You control how it changes.
Key Takeaway: Encapsulation in JavaScript means hiding internal state and exposing controlled access points, achieved through closures, conventions, or private fields — protecting your data while keeping interfaces clean.