Skip to main content
FREE Mock interview & resume review with Sumit. Free right now, no payment needed.Book a slot

Scope, Scope Chain & Closures — JavaScript interview guide

2 / 23How JavaScript RunsHigh priorityMedium 35 min

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

Creation phaseStep 1/10
script.js
1function makeCounter() {
2 let count = 0;
3 return function increment() {
4 count++;
5 return count;
6 };
7}
8
9const counter = makeCounter();
10console.log(counter());
11console.log(counter());
Call Stack
last in, first out
Globalrunning
Memory / Scope
Global
makeCounterƒ makeCounter()
counter<uninitialized>
Console

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 directly

The 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 2

Remember 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

  1. Write a function once(fn) that lets fn run only one time.
  2. Fix the var loop using an IIFE instead of let.

Keep learning