Sub topic 9
Private State with Closures
This chapter assumes you have read the earlier chapters on what a closure is and on how closures capture variables rather than snapshots. You should be comfortable with object literals, methods, and returning functions from functions. Here we put those ideas to work and use closures to hide data from the code around it.
The Problem with Public Properties
A plain object exposes every property to every piece of code that holds a reference to it. Nothing stops a caller from putting the object into a state that makes no sense.
const account = {
balance: 100,
deposit(amount) {
this.balance += amount;
return this.balance;
}
};
account.balance = -5000; // nothing prevents this
account.balance = 'banana'; // or this
console.log(account.deposit(10)); // 'banana10'The deposit method has rules in mind: the balance is a number, and it changes only through deposits. Any caller can bypass deposit, so the object cannot enforce those rules. An invariant is a condition that should always hold for an object. Public properties make invariants impossible to guarantee.
Hiding State Inside a Closure
A closure gives you a variable that only certain functions can reach. If you declare the state as a local variable and return methods that close over it, those methods become the only way in.
function createAccount(initialBalance) {
let balance = initialBalance;
return {
deposit(amount) {
balance += amount;
return balance;
},
getBalance() {
return balance;
}
};
}
const account = createAccount(100);
account.deposit(50);
console.log(account.getBalance()); // 150
console.log(account.balance); // undefinedbalance is not a property of the returned object. It is a binding in the lexical environment that createAccount created when it ran. Once createAccount returns, no name in any outer scope refers to that environment. Only deposit and getBalance still hold a reference to it, through their internal link to the scope they were defined in.
account.balance is undefined because the object has no such property. Setting account.balance = 1e9 would add a new, unrelated property and leave the real balance alone.
Enforcing Invariants
Once the methods are the only way to reach the state, they can check every change. This is the real reason to make state private.
function createAccount(initialBalance) {
if (typeof initialBalance !== 'number' || initialBalance < 0) {
throw new RangeError('Initial balance must be a non-negative number');
}
let balance = initialBalance;
function assertAmount(amount) {
if (typeof amount !== 'number' || !Number.isFinite(amount) || amount <= 0) {
throw new RangeError('Amount must be a positive number');
}
}
return {
deposit(amount) {
assertAmount(amount);
balance += amount;
return balance;
},
withdraw(amount) {
assertAmount(amount);
if (amount > balance) {
throw new Error('Insufficient funds');
}
balance -= amount;
return balance;
},
getBalance() {
return balance;
}
};
}
const acct = createAccount(100);
acct.withdraw(30);
console.log(acct.getBalance()); // 70
try {
acct.withdraw(500);
} catch (err) {
console.log(err.message); // 'Insufficient funds'
}The helper assertAmount is private too. It lives in the same environment as balance, so the methods can call it, and outside code cannot. You can hide helper functions as well as data this way.
Each call to createAccount runs the function body again, which creates a new environment with its own balance. Two accounts never share state, even though their methods have identical source code.
Common Errors
The pattern is short, and the bugs that come with it follow a few repeating shapes.
Returning a Snapshot Instead of Live Access
Putting a private variable directly into the returned object copies its current value. That copy does not change later.
function createCounter() {
let count = 0;
return {
count, // copies 0 into a property
increment() {
count += 1;
}
};
}
const c = createCounter();
c.increment();
console.log(c.count); // 0, the property never updatesThe shorthand { count } means { count: count }. The value is read once, when the object is created. To expose a read-only view that stays current, use a getter, which runs a function each time the property is read:
function createCounter() {
let count = 0;
return {
get count() {
return count;
},
increment() {
count += 1;
}
};
}
const c = createCounter();
c.increment();
console.log(c.count); // 1
c.count = 99; // ignored (throws a TypeError in strict mode)
console.log(c.count); // 1Leaking a Mutable Reference
Privacy covers the variable, not the value it holds. If the private variable refers to an array or object and you return that reference, callers can change it in place.
function createTodoList() {
const items = [];
return {
add(text) {
items.push(text);
},
getItems() {
return items; // hands out the real array
}
};
}
const list = createTodoList();
list.add('write tests');
list.getItems().push('skip validation'); // bypasses add()
console.log(list.getItems()); // ['write tests', 'skip validation']Return a copy instead: return [...items]; for arrays, or { ...obj } for plain objects. Both copies are shallow. If the elements are objects themselves, callers can still change them, so copy deeper (for example with structuredClone) or store immutable values.
Expecting Methods Added Later to See the State
Only functions defined inside the enclosing function's scope close over its variables. A method attached from outside has no access to them.
const account = createAccount(100);
account.reset = function () {
balance = 0; // this 'balance' is not the private one
};
try {
'use strict';
account.reset();
} catch (err) {
console.log(err.name);
}In non-strict code, balance = 0 quietly creates a global variable, which is worse than an error. In strict mode or an ES module it throws a ReferenceError. Either way, the private balance does not change. To add behavior that needs the state, add it inside createAccount.
Relying on this Inside the Methods
Closure-based methods read state through the scope chain, not through this. That means they keep working when you detach them:
const acct = createAccount(100);
const { deposit, getBalance } = acct;
deposit(25);
console.log(getBalance()); // 125If you mix in this.something references, detaching the method breaks them. Keep closure-based objects free of this and you can pass the methods around as callbacks safely.
Closures Compared with Other Privacy Options
JavaScript now has several ways to mark data as private. They differ in how strong the privacy is and in what they cost.
| Approach | Truly private | Memory per instance | Inspectable in DevTools | Works with `instanceof` |
|---|---|---|---|---|
| Underscore convention (`this._balance`) | No, convention only | Methods shared on prototype | Yes | Yes |
| Closure variables | Yes | Each instance gets its own copies of the methods | Yes, under the function's scopes | No, unless you build that yourself |
| Class private fields (`#balance`) | Yes | Methods shared on prototype | Yes | Yes |
Class private fields look like this:
class Account {
#balance;
constructor(initialBalance) {
this.#balance = initialBalance;
}
deposit(amount) {
this.#balance += amount;
return this.#balance;
}
getBalance() {
return this.#balance;
}
}
const a = new Account(100);
a.deposit(50);
console.log(a.getBalance()); // 150Use these criteria to choose:
- Choose closures when you want detachable methods that ignore
this, when you prefer functions to classes, or when you need private state inside a single function such as a callback or a cache. - Choose
#fields when you create many instances and want methods shared on the prototype, or when you need inheritance andinstanceof. - Use the underscore convention only when you want "private by agreement" and need tests or subclasses to reach in freely.
Trade-offs to Keep in Mind
- Testing. You cannot assert on private variables directly. Test through the public methods. That is usually the better test anyway, because it checks behavior instead of internals.
- Serialization.
JSON.stringify(account)produces{}because methods and closure variables are not serialized. Add atoJSON()method if you need a representation. - Debugging. The private state is still visible in browser DevTools and the Node inspector under the function's
[[Scopes]]. It is private from other code, not secret from the person running it. Never treat closure privacy as a security boundary for secrets in client-side code.
The next chapter turns this pattern into a general technique for building objects, called factory functions.
Exercise
The following code prints 0 instead of 2. Explain why, and change createScore so that score.value reports the current total and cannot be overwritten from outside. function createScore() { let total = 0; return { value: total, add(points) { total += points; } }; } const score = createScore(); score.add(2); console.log(score.value);
Show answer
The property value: total copies the number 0 once, when the object literal is evaluated, so later changes to total do not reach it. Replace it with a getter that reads the closure variable each time: return { get value() { return total; }, add(points) { total += points; } };. Because there is no setter, assigning to score.value is ignored (or throws a TypeError in strict mode), and score.value now prints 2.
Exercise
A createInventory function keeps a private array items and exposes getItems() { return items; }. A caller runs inventory.getItems().length = 0. What happens, and how do you prevent it?
Show answer
Setting length to 0 empties the real private array, because getItems returned a reference to it, not a copy. The closure protects the variable binding, not the contents of the object it refers to. Return a copy instead, for example return [...items]; or return items.slice();. If the items are objects, deep-copy them (for example with structuredClone) or store frozen values so callers cannot change them in place.
Exercise
Write a createRateLimiter(limit) function that returns an object with tryAcquire() and remaining(). tryAcquire returns true and uses one slot while slots remain, otherwise false. The used count must not be readable or writable directly.
Show answer
function createRateLimiter(limit) { let used = 0; return { tryAcquire() { if (used >= limit) return false; used += 1; return true; }, remaining() { return limit - used; } }; } Here used and limit both live in the closure. const r = createRateLimiter(2); r.tryAcquire(); r.tryAcquire(); r.tryAcquire() returns false, r.remaining() returns 0, and r.used is undefined.