Closures
A closure is a function that remembers the variables of its outer scope, even after the outer function has finished. Closures give private state, explain the classic var-in-a-loop bug, and are behind stale values in React callbacks.
10.1 Why is it used?
- A global count can be read and changed by any part of the code.
- Some other code sets count = 100 by mistake, and the next call gives 101.
- In a big project it is hard to find out who changed it.
- We need a variable only increment can access: a closure gives exactly that.
JavaScript
let count = 0; function increment() { count = count + 1; return count;} console.log(increment());console.log(increment()); count = 100;console.log(increment());Output
> 1> 2> 10110.2 Fix: a counter with a closure
- count is now a local variable of createCounter; nobody outside can even see it.
- createCounter returns an inner function that adds one to count.
- createCounter has already finished, yet counter() gives 1, then 2: the inner function remembered count.
- A new counter (other) starts again at 1: every call to createCounter gets its own count.
JavaScript
function createCounter() { let count = 0; return function () { count = count + 1; return count; };} const counter = createCounter();console.log(counter());console.log(counter()); const other = createCounter();console.log(other());Output
> 1> 2> 110.3 How a closure works
- When the inner function is created it keeps a reference to the variables around it, like a backpack.
- The outer function finishes, but the variables in the backpack stay alive.
- Every time the inner function is called it uses the same count from its backpack.
- Step 1
1.createCounter() runs: let count = 0
- Step 2
2.Inner function created: keeps a reference to count (backpack)
- Step 3
3.createCounter finishes and returns the inner function
- Step 4
4.count stays alive inside the backpack
- Step 5
5.counter() called: count = 1, then 2 (same count)
Closure = function + its lexical environment
10.4 Private state
- createWallet keeps balance as a local variable and returns an object with add and getBalance.
- Both methods share the same balance: 500 + 200 = 700.
- wallet.balance is undefined: nobody outside can change the balance directly.
JavaScript
function createWallet(initial) { let balance = initial; return { add(amount) { balance = balance + amount; }, getBalance() { return balance; }, };}const wallet = createWallet(500);wallet.add(200);console.log(wallet.getBalance());console.log(wallet.balance);Output
> 700> undefined10.5 Checkpoint: var in a loop
- A var loop with setTimeout prints 3 3 3, not 0 1 2.
- var is function scoped, so all three callbacks close over one single i.
- By the time the timers run, the loop has finished and i is 3.
- Fix: let is block scoped, so every round gets a new i and each callback remembers its own value (0 1 2).
JavaScript
// Wrongfor (var i = 0; i < 3; i++) { setTimeout(() => console.log(i), 100);}JavaScript
// Rightfor (let i = 0; i < 3; i++) { setTimeout(() => console.log(i), 100);}- Step 1
1.Loop runs 3 times and schedules 3 callbacks
- Step 2
2.var: all 3 callbacks share one i
- Step 3
3.Loop ends, the shared i is 3
- Step 4
4.Timers fire: 3 3 3
- Step 5
5.let: a new i per round, each closure keeps its own: 0 1 2
10.6 A closure keeps a reference, not a copy
- showPrice was created when price was 100, but price became 200 before the call.
- The output is 200: a closure always reads the current value of the variable.
JavaScript
let price = 100;const showPrice = () => console.log(price); price = 200;showPrice();Output
> 20010.7 Stale closure
- A stale closure shows an old value.
- msg is built only once, when items was 0, so after two adds log still prints Items: 0.
- Fix: make msg a function so every call reads the latest items (Items: 2).
- React has the same problem when a callback sees old state (covered in the React part).
JavaScript
// Wrongfunction createCart() { let items = 0; const msg = `Items: ${items}`; const add = () => { items = items + 1; }; const log = () => console.log(msg); return { add, log };} const cart = createCart();cart.add();cart.add();cart.log();JavaScript
// Rightfunction createCart() { let items = 0; const msg = () => `Items: ${items}`; const add = () => { items = items + 1; }; const log = () => console.log(msg()); return { add, log };} const cart = createCart();cart.add();cart.add();cart.log();10.8 Comparison: global variable vs closure
| Point | Global variable | Closure |
|---|---|---|
| Who can change it | Any code | Only the returned functions |
| Separate instances | One shared value | Each call gets its own (counter, other) |
| Bug risk | Changed elsewhere (count = 100) | Stale value if built once |
| Memory | Lives for the whole program | Lives while a reference to the inner function exists |
10.9 Rules
- Use let or const in loops and callbacks, never var.
- Keep data that must not change from outside private inside a closure; return only the functions that are needed.
- Variables a closure holds stay in memory: when you are done with big data or a timer, remove the reference.
10.10 Interview tips
- A closure is the combination of a function and its lexical environment.
- The function remembers the variables of its outer scope even after the outer function has finished.
- Give the counter or private wallet example.
- Explain the var loop bug (3 3 3) and the let fix (0 1 2); mention that a closure holds a reference, not a copy.