Encapsulation in JavaScript Closures vs Private Fields
Compare closures, hash private fields and underscore conventions for encapsulation in JavaScript, with trade-offs in copying, testing and inheritance.

Encapsulation means an object keeps its internal state to itself and offers a small, deliberate interface to everyone else. The benefit is practical: if callers cannot touch the internals, you can change them later without breaking anyone, and you can enforce rules, such as a balance that never goes negative, in one place. JavaScript gives you four ways to get there, and they are not equivalent. Closures have worked since the beginning, #private fields arrived in ES2022, WeakMap private data is the older class-based trick and a leading underscore is only a convention. This post compares encapsulation in JavaScript across those options with the same example in each, shows what each one costs and says when to choose which. All examples run on Node.js 24 and print their output.
The example: a bank account
The rule to protect is simple: the balance can change only through deposit and withdraw, and a withdrawal larger than the balance is refused. Each version below is checked with the same calls.
Option 1: closures
A function creates a variable and returns an object whose methods can see it. Nothing outside the function can reach the variable, since it is not a property of anything.
function createAccount(initial) {
let balance = initial;
return {
deposit(amount) {
balance += amount;
},
withdraw(amount) {
if (amount > balance) throw new Error("insufficient funds");
balance -= amount;
},
getBalance() {
return balance;
},
};
}
const account = createAccount(100);
account.deposit(50);
console.log(account.getBalance());
console.log(account.balance);
try {
account.withdraw(500);
} catch (error) {
console.log(error.message);
}150
undefined
insufficient fundsThe privacy is real, and it works in every JavaScript engine since the language began. The costs are different. Each call to createAccount creates a new copy of every method, so a thousand accounts hold a thousand sets of functions, where a class would share one. The object has no prototype to hold shared methods, so instanceof checks do not apply. And you cannot add a method later that sees the private variable, since only functions defined inside the factory can.
Option 2: #private fields
A class can declare fields with a leading #. The engine enforces that they are readable and writable only from code inside the class body.
class Account {
#balance;
constructor(initial) {
this.#balance = initial;
}
deposit(amount) {
this.#balance += amount;
}
withdraw(amount) {
if (amount > this.#balance) throw new Error("insufficient funds");
this.#balance -= amount;
}
get balance() {
return this.#balance;
}
}
const account = new Account(100);
account.deposit(50);
console.log(account.balance);
console.log(account.hasOwnProperty("#balance"));
try {
account.withdraw(500);
} catch (error) {
console.log(error.message);
}150
false
insufficient fundsThe methods live on the shared prototype, so memory use is low and instanceof works. Privacy is enforced by the language: trying to read account.#balance outside the class is a syntax error, not just an undefined value. The field does not appear in Object.keys, JSON.stringify or for...in. This is the default choice for new class-based code in Node.js 24 and in all current browsers.
Private fields have a few sharp edges. They are not inherited by name: a subclass cannot read its parent's #balance, so a parent needs a protected-style accessor method for subclasses. Accessing a private field on an object that was not created by the class throws a TypeError, which you can test with the #field in obj syntax:
class Account {
#balance = 0;
static isAccount(value) {
return #balance in value;
}
}
console.log(Account.isAccount(new Account()), Account.isAccount({}));true falseThis "brand check" gives a reliable way to ask whether an object is a genuine instance, which instanceof cannot promise across realms or with a modified prototype. Also, a proxy wrapping a class instance breaks private field access, because the proxy is a different object than the one that holds the private slot, and methods that read this.#balance throw when this is the proxy.
Option 3: WeakMap private data
Before # fields, classes kept private state in a module-level WeakMap keyed by the instance.
const balances = new WeakMap();
class Account {
constructor(initial) {
balances.set(this, initial);
}
deposit(amount) {
balances.set(this, balances.get(this) + amount);
}
get balance() {
return balances.get(this);
}
}
const account = new Account(100);
account.deposit(50);
console.log(account.balance, Object.keys(account));150 []It gives real privacy, since only code that can see the WeakMap variable can reach the data, and the entry is garbage collected when the instance is. But it is verbose and slower to read than a field, and the privacy depends on the map staying inside the module. Today it is mainly useful when you must support a runtime without # fields, which is rare.
Option 4: the underscore convention
A leading underscore, as in this._balance, marks a property as internal by agreement. Nothing enforces it.
class Account {
constructor(initial) {
this._balance = initial;
}
}
const account = new Account(100);
account._balance = -9999;
console.log(account._balance, Object.keys(account));-9999 [ '_balance' ]Anyone can bypass the rules, the property shows up in Object.keys and in JSON output, and the invariant of a non-negative balance is gone. The advantage is that tests and debuggers can see it, and it works with proxies and with older tools. Use it when the audience is your own team, enforcement is not the goal and visibility helps, such as in a library's internal helper that you do not want to freeze behind a private field.
Comparing them
| Feature | Closure | #private | WeakMap | Underscore |
|---|---|---|---|---|
| Truly inaccessible | Yes | Yes | Yes | No |
| Methods shared on prototype | No | Yes | Yes | Yes |
instanceof and inheritance | No | Yes | Yes | Yes |
Visible to JSON and Object.keys | No | No | No | Yes |
Works with Proxy wrapping | Yes | No | Yes | Yes |
| Visible in console output | No | No | No | Yes |
| Minimum runtime | Any | ES2022 | ES2015 | Any |
Note that console.log and util.inspect do not print #private fields, so logging an instance will not reveal them. Both private fields and closure variables are visible in a debugger's scope pane while you are stopped inside a method, which is the place to look when you need to see them.
Testing private state
Encapsulation makes direct testing of private state impossible, and that is the point. Test through the public interface: deposit, withdraw and read the balance. If you find yourself wanting to peek inside, it is often a sign that the class does too much and one part should be a separate object with its own public interface. Resist exposing a test-only getter or switching to underscores for the test's sake, because that weakens the design for a reason that has a better answer.
Where the advice stops
Encapsulation is not security. A closure or a private field keeps other code in the same program honest, but it does not protect secrets from someone who can run code in your process: a debugger, a heap snapshot or a modified runtime can read it. Never rely on private fields to hide credentials from untrusted code in the same realm. And do not wrap everything: plain data objects with public properties are fine when they have no invariants to protect. Encapsulate where a rule must hold, not by reflex.
Choosing in practice
For a class that will have many instances, such as a model object or a parser token, use #private fields: the methods stay on the prototype and the engine enforces the boundary. For a module that exposes a single service, a closure inside a factory function is often the tidiest form, because the module itself is the boundary and the variables never leave it. For a library that must work with proxies, such as one used inside a reactive framework, closures and WeakMap avoid the proxy problem that private fields have. And for an internal data holder with no invariants, a plain object with public properties is the honest choice, since hiding fields that nobody needs to protect adds code and no safety.
Migrating from underscores
Many older codebases use underscore properties, and moving them to #private is mechanical but not risk-free. Search for every access to _name first, because tests, subclasses and other modules may read it. Each external read needs either a public accessor or a design change. Rename in one commit and let the engine's syntax errors point out the remaining outside accesses, since a reference to obj.#name outside the class fails at parse time rather than at runtime. Subclasses that touched the parent's underscore field need a protected-style method on the parent. Serialization is the last trap: JSON.stringify used to include _name and no longer will, so add a toJSON() method if anything depends on the old output.


