Sub topic 9
Private State with Closures
This chapter assumes you know what a closure is and that closures capture variables, not snapshots of their values. It also assumes you are comfortable returning objects from functions.
The Problem: Anyone Can Change a Property
Properties on a plain object are public. Any code holding the object can read or overwrite them:
const account = { balance: 100 };
account.balance = -5000; // nothing stops this
console.log(account.balance); // -5000You often want some data that only specific functions can change. A closure gives you this. If a variable lives inside a function and only the functions created there can reach it, outside code has no way to read or change it directly.
Hiding a Variable Behind Methods
function createAccount(initialBalance) {
let balance = initialBalance;
return {
deposit(amount) {
if (amount <= 0) {
throw new Error('Deposit must be positive');
}
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 a local variable of createAccount. The returned object has no balance property. deposit and getBalance close over the same binding, so a change made by one is visible to the other. The only way to change the balance is through deposit, and deposit enforces its rule.
Each call to createAccount creates a new lexical environment, so each account has its own separate balance.
Common Errors
Expecting a Property to Track the Variable
function createCounter() {
let count = 0;
return {
count,
increment() { count += 1; }
};
}
const c = createCounter();
c.increment();
console.log(c.count); // 0The shorthand count copies the value 0 into a property when the object is created. Later changes to the variable do not affect that property. If you need read access, expose a method such as getCount() or a getter: get count() { return count; }.
Leaking a Mutable Reference
Keeping an array or object private does not protect it if a method returns the reference itself:
function createTodoList() {
const items = [];
return {
add(item) { items.push(item); },
getItems() { return [...items]; } // return a copy, not items
};
}
const list = createTodoList();
list.add('write tests');
list.getItems().push('hack'); // changes only the copy
console.log(list.getItems()); // ['write tests']If getItems returned items directly, callers could change the private array. Return copies, or freeze the data, when you hand it out.
Expecting Methods to Be Shared
Every object created this way gets its own copies of its methods. That is fine for a few objects. For many thousands of instances, class methods on a shared prototype use less memory.
Exercise
Add a withdraw(amount) method to createAccount that throws an error if the amount exceeds the current balance, and otherwise subtracts it and returns the new balance. Why can't outside code skip this check?
Show answer
Add withdraw(amount) { if (amount > balance) { throw new Error('Insufficient funds'); } balance -= amount; return balance; } to the returned object. Outside code cannot skip the check because balance is not a property of the object. It exists only in the closure that the methods share, so the methods are the only way to change it.
Exercise
Given const a = createAccount(10); const b = createAccount(10); a.deposit(5);, what does b.getBalance() return, and why?
Show answer
It returns 10. Each call to createAccount creates a new environment with its own balance binding, so changes to a do not affect b.