Scope, Scope Chain & Closures — JavaScript interview guide
Scope, Scope Chain & Closures
Scope decides where a variable can be used. A closure is a function that remembers the variables from the place it was created, even after that place has finished running.
See it run
Press Play, or step with Next. Watch the highlighted line, the Call Stack and memory change together.
How a closure keeps a variable alive
1function makeCounter() {2let count = 0;3return function increment() {4count++;5return count;6};7}89const counter = makeCounter();10console.log(counter());11console.log(counter());
| makeCounter | ƒ makeCounter() |
| counter | <uninitialized> |
nothing printed yet
What happens:Creation phase: makeCounter is stored fully, counter (const) is in the TDZ.
Tip: click the box and use ← → keys to step, space to play.
Explained simply
Scope and the scope chain
JavaScript has global scope, function scope and block scope ({ } with let/const). var ignores block scope.
If a variable is not found in the current scope, JS looks in the outer scope, then the next one, up to global. This lookup path is the scope chain, and it is decided by where code is WRITTEN (lexical scope).
Closures
When an inner function uses variables from an outer function, it keeps a reference to them. If the inner function is returned or passed somewhere, those variables stay alive.
Closures are used for private variables, function factories, memoization, debounce and React hooks.
function createBank() {
let balance = 0; // private
return {
deposit(x) { balance += x; return balance; },
getBalance() { return balance; },
};
}
const acc = createBank();
acc.deposit(100);
acc.getBalance(); // 100
acc.balance; // undefined — cannot be touched directlyThe classic loop question
With var, all callbacks share ONE variable, so they all see its final value. With let, each loop iteration gets a new binding.
for (var i = 0; i < 3; i++) setTimeout(() => console.log(i)); // 3 3 3
for (let j = 0; j < 3; j++) setTimeout(() => console.log(j)); // 0 1 2Remember this
- Lexical scope: what a function can see depends on where it is written, not where it is called.
- A closure = function + the variables it remembers from its outer scope.
- Closures keep variables alive, which can cause memory leaks if held for too long.
Interview questions
What is a closure? Give a real use case.
A function bundled with references to its outer scope variables. Real uses: private state (counter, bank account), debounce/throttle keeping a timer, memoize keeping a cache.
Why does the var loop with setTimeout print 3 3 3?
var is function-scoped, so there is only one i. By the time the callbacks run, the loop has finished and i is 3. let creates a new i per iteration.
Practice
- Write a function once(fn) that lets fn run only one time.
- Fix the var loop using an IIFE instead of let.