Practical Closures

Private State

Example

Variables inside a closure cannot be reached from outside: only through the functions you return.

function createAccount(initial) {
  let balance = initial;            // private
  return {
    deposit(amount) { balance += amount; return balance; },
    withdraw(amount) {
      if (amount > balance) throw new Error("Insufficient funds");
      balance -= amount;
      return balance;
    },
    getBalance: () => balance,
  };
}
const acc = createAccount(1000);
acc.deposit(500);
acc.withdraw(200);
console.log(acc.getBalance());
console.log(acc.balance);           // not accessible

Output

1300
undefined

Function Factories and Memoization

Example

A closure can cache results of an expensive function:

function memoize(fn) {
  const cache = {};
  return (n) => {
    if (n in cache) return "cached " + cache[n];
    return (cache[n] = fn(n));
  };
}
const slowSquare = (n) => n * n;
const fastSquare = memoize(slowSquare);
console.log(fastSquare(9));
console.log(fastSquare(9));

Output

81
cached 81