Javascript Fundamentals ยท Interview Fundamentals

Closures

closures

Closures

Call a function, and when it returns, the variables it created are usually gone. Here is one whose variable survives anyway:

function makeCounter() {
  let count = 0;
  return function () {
    count += 1;
    return count;
  };
}

const next = makeCounter();
next(); // 1
next(); // 2

makeCounter has already returned by the time next() runs, yet count keeps its value and the returned function can still update it. A function bundled with the scope it was defined in is a closure. It holds the variables themselves, not a copy of their values.

Each call to makeCounter creates a fresh count. Two counters do not share state:

const a = makeCounter();
const b = makeCounter();
a(); // 1
a(); // 2
b(); // 1

Closures are how you get private state, factory functions, and callbacks that remember where they came from. A loop variable captured by a closure is the classic trap: var gives every callback the same binding, while let gives each iteration its own.

You are about to answer a short quiz on closures.

  1. A closure is a function bundled with the lexical scope it was defined in.
  2. A function that keeps access to the scope it was defined in is called a ___.
  3. Two counters returned by separate calls to the same factory function share one captured variable.
  4. Inside a for loop, a callback created with ___ gets a fresh binding on every iteration.
  5. A closure lets an inner function read and update a variable after the outer function has returned.
  6. Arrow functions cannot form closures.