Encapsulation
Encapsulation is keeping an object's internals hidden and exposing a small API. In JavaScript that means closures, module scope, or #private fields — not a compiler-enforced private keyword on ordinary properties.
Detailed Explanation
An object that lets every caller write user._balance = -9 has no boundary. Encapsulation is the boundary: the rest of the program talks to deposit and withdraw, and the representation of the balance can change without a hunt through the codebase.
JavaScript historically had no private properties. The culture used conventions. A leading underscore (_balance) means "please do not touch this". It is a comment. user._balance still works. Object.freeze can lock a surface, but it is shallow and opt-in.
Three real mechanisms exist today.
Closures. A factory function keeps variables in its environment and returns methods that close over them. Nothing on the returned object can see balance except those methods. This is the oldest strong encapsulation in the language. The cost is that each instance gets its own copies of the methods; they are not on a shared prototype.
Module scope. Bindings that you do not export are invisible to other files. A module-level cache or a helper stays private without being attached to an instance. This is encapsulation at file grain, not object grain.
Private fields and methods (#balance, #audit()). These are per-instance (or static, with static #n) and are only readable in the class body that declared them. A subclass cannot read a parent's # field. in can detect a private field (#balance in obj) from inside the class, which is the branded-check pattern. Outside the class, #balance is a syntax error.
Getters and setters are not encapsulation by themselves. They are a way to put a function behind property syntax. A getter that returns a mutable inner object (get items() { return this.#items; }) leaks the representation. Return a copy, or return a read-only view.
What it costs you: convenience and tooling. Private fields do not survive JSON.stringify or spread ({ ...user } drops # keys). Tests cannot poke #balance without a dedicated hook. Closures hide state from the prototype, which uses more memory. Underscore fields hide nothing.
Reach for # fields when you have a class and a real invariant (balances, tokens, open sockets). Reach for module-private functions when the secret is not per-instance. Reach for a closure factory when you want privacy without class. Do not treat _name as safety.
Code Examples
function makeWallet(opening) {
let cents = opening; // closed over, not on the object
return {
deposit(amount) {
cents += amount;
return cents;
},
read() {
return cents;
},
};
}
const w = makeWallet(100);
console.log(w.read()); // => 100
console.log(w.cents); // => undefinedclass Wallet {
#cents;
constructor(opening) {
this.#cents = opening;
}
deposit(amount) {
this.#cents += amount;
return this.#cents;
}
}
const wallet = new Wallet(100);
console.log(wallet.deposit(40)); // => 140
console.log(Object.keys(wallet)); // => []class User {
constructor(email) {
this._email = email; // convention only
}
}
const u = new User("ada@example.com");
u._email = "eve@example.com";
console.log(u._email); // => eve@example.comCommon Gotchas
A leading underscore is not privacy
it is a naming habit. Production code and tests can and will write to `_fields`.
Returning an inner array from a getter leaks it
the caller can `.push` and mutate your invariant. Copy, freeze, or expose methods.
`{ ...instance }` and `JSON.stringify` omit private fields
persist through an explicit `toJSON` that lists the public data you intend to save.
Closures do not share methods on the prototype
a million instances means a million function objects. Classes with `#` fields share methods and still hide state.