JavaScript Private State with Closures
Private state is a variable that only chosen functions can reach. A closure hides the variable inside the outer function and hands out methods that share it.
A bank account
The balance lives inside makeAccount. Deposit and withdraw change it, and getBalance reads it. The balance is not a property, so reading it gives undefined.
function makeAccount(start) {
let balance = start;
return {
deposit: function (amount) { balance = balance + amount; },
withdraw: function (amount) { balance = balance - amount; },
getBalance: function () { return balance; }
};
}
const account = makeAccount(100);
account.deposit(50);
account.withdraw(30);
console.log(account.getBalance());
console.log(account.balance);A counter with methods
Up and down share one hidden count. The value method is the only way to read it.
function makeCounter() {
let count = 0;
return {
up: function () { count = count + 1; },
down: function () { count = count - 1; },
value: function () { return count; }
};
}
const counter = makeCounter();
counter.up();
counter.up();
counter.down();
console.log(counter.value());Outside writes cannot reach inside
Writing account.balance only adds a plain property to the object. The hidden balance stays untouched.
function makeAccount(start) {
let balance = start;
return {
deposit: function (amount) { balance = balance + amount; },
getBalance: function () { return balance; }
};
}
const account = makeAccount(100);
account.balance = 1000000;
console.log(account.getBalance());
console.log(account.balance);Example
function makeAccount(start) {
let balance = start;
return {
deposit: function (amount) { balance = balance + amount; },
withdraw: function (amount) { balance = balance - amount; },
getBalance: function () { return balance; }
};
}
const ana = makeAccount(100);
const ben = makeAccount(50);
ana.deposit(25);
ben.withdraw(10);
console.log(ana.getBalance());
console.log(ben.getBalance());Key points
- Private state: a variable hidden inside a function, reached only through the functions it returns
- The returned methods all share the one hidden variable.
- Code outside cannot read or change the hidden variable by name.
- Reading the hidden variable as a property gives undefined.
- Each call to the outer function makes a new hidden variable.
In this example, makeAccount builds two accounts with separate hidden balances. Ana deposits 25, so her balance is 125. Ben withdraws 10, so his balance is 40. Each account keeps its own balance.
Try it Yourself
Edit the code, then press Run.
Runs in your browser — the preview under the editor is the real result. Nothing is sent to a server. The code runner panel (right) does the same with more room.
Exercise
How does code outside a closure change the hidden balance?