Closures

Updated · 9 min read
hardES2026javascriptclosuresscopefunctionsinterview

A closure is a function together with the variables from the scope where it was created. In JavaScript, every function keeps a link to the environment it was defined in, so it can keep reading and changing those variables even after the outer function has returned. Closures are how factories remember their settings, how event handlers remember their data, and how JavaScript code had private state long before classes had #private fields. They are also one of the most common interview topics.

In One Minute

  • A function can use variables from the scope where it was written (lexical scope).
  • When the outer function returns, those variables stay alive as long as an inner function still refers to them.
  • Each call to the outer function creates a new set of variables, so each returned function has its own.
  • Closures give private state: variables nobody outside can reach except through the returned functions.
  • A closure keeps everything it refers to in memory; drop references you no longer need.

A First Closure

first.js▶ Try it
function makeGreeting(name) {
  const greeting = `Hello, ${name}!`;
  return function () {
    return greeting;
  };
}
 
const greetNavika = makeGreeting("Navika");
const greetAdvitha = makeGreeting("Advitha");
 
console.log(greetNavika());
console.log(greetAdvitha());
Output
Hello, Navika!
Hello, Advitha!

Explanation: makeGreeting finished running long before greetNavika() was called, yet the inner function still knows greeting. When the inner function was created, it captured a reference to the environment of that particular call to makeGreeting, where greeting lives. The two calls created two separate environments, so each returned function has its own greeting.

Closures Capture Variables, Not Values

A closure holds a live link to the variable itself, not a snapshot of its value at creation time. If the variable changes, the closure sees the change:

live.js▶ Try it
let rate = 2;
const lateFee = (days) => days * rate;
 
console.log(lateFee(10));
rate = 5;
console.log(lateFee(10));
Output
20
50

That is useful (a closure always sees current data) and occasionally surprising: the loop bug later in this lesson is exactly this behavior.

Private State

Variables inside a function are invisible from outside. By returning functions that use them, you control exactly how they can be read and changed:

private.js▶ Try it
function createAccount(owner, opening) {
  let balance = opening;
  const history = [];
 
  return {
    pay(amount) {
      if (!(amount > 0)) throw new RangeError("Payment must be positive");
      balance -= amount;
      history.push(-amount);
    },
    charge(amount) {
      balance += amount;
      history.push(amount);
    },
    get balance() {
      return balance;
    },
    statement() {
      return `${owner}: ${history.join(", ")} -> $${balance}`;
    },
  };
}
 
const account = createAccount("Srihitha", 450);
account.pay(200);
account.charge(30);
console.log(account.balance);
console.log(account.statement());
 
account.balance = 0;
console.log(account.balance, Object.keys(account));
Output
280
Srihitha: -200, 30 -> $280
280 ['pay', 'charge', 'balance', 'statement']

Explanation: balance and history are not properties of the returned object; they exist only in the closure. The only way to change the balance is through pay and charge, which validate their input. Assigning account.balance = 0 does nothing, because balance is a getter with no setter. This is the module pattern, used heavily before ES modules and #private class fields existed.

Each Call, Its Own Closure

counters.js▶ Try it
function makeCounter() {
  let count = 0;
  return {
    increment: () => ++count,
    current: () => count,
  };
}
 
const receipts = makeCounter();
const reminders = makeCounter();
 
receipts.increment();
receipts.increment();
reminders.increment();
 
console.log(receipts.current(), reminders.current());
Output
2 1

Both counters were made by the same function, but each call to makeCounter created a new count. Within one counter, increment and current share the same count, because they were created in the same call.

The Loop Bug

The classic closure puzzle: functions created in a loop all see the same variable when it is declared with var:

loop-let.js▶ Try it
const handlers = [];
for (let i = 1; i <= 3; i++) {
  handlers.push(() => `Button ${i}`);
}
console.log(handlers.map((h) => h()));
Output
['Button 1', 'Button 2', 'Button 3']

Explanation: with var, there is one i for the whole function, and every closure captures that one variable. By the time the closures run, the loop has finished and i is 4. With let, the language creates a fresh i per round (copying the current value in), so each closure captures its own.

The pre-2015 fix was an IIFE (an immediately invoked function, covered in the recursion lesson) that created a new scope per round: (function (n) { handlers.push(() => n); })(i).

Closures in Everyday Code

You use closures constantly, often without noticing:

everyday.js▶ Try it
function attachReminder(student, delayMs) {
  setTimeout(() => {
    console.log(`Reminder: ${student.name} owes $${student.balance}`);
  }, delayMs);
}
attachReminder({ name: "Advitha", balance: 45 }, 10);
 
const minimum = 50;
const large = [120, 30, 85].filter((amount) => amount >= minimum);
console.log(large);
 
const usd = new Intl.NumberFormat("en-US", { style: "currency", currency: "USD" });
const format = (n) => usd.format(n);
console.log(format(1234.5));
Output
[120, 85]
$1,234.50
Reminder: Advitha owes $45

The timer callback remembers student after attachReminder returned; the filter callback reads minimum from the outer scope; format reuses usd. Event listeners, promise callbacks and React hooks all rely on the same mechanism.

Closures and Memory

A closure keeps its captured variables alive. Usually that's exactly what you want, but it means anything a long-lived closure references can't be garbage collected:

memory.js
function setupReport(button, allPayments) {
  const bigTable = buildHugeTable(allPayments);         // megabytes of data
  button.addEventListener("click", () => {
    console.log(`Rows: ${bigTable.length}`);            // the listener keeps bigTable alive
  });
}
// As long as the button and its listener exist, bigTable stays in memory.

To let memory be freed: capture only what you need (const count = bigTable.length before creating the listener), remove listeners and clear timers when they're no longer needed (an AbortController signal helps), and avoid storing closures in long-lived places such as global arrays. The memory lesson covers leaks in depth.

Under the Hood

Every function object has an internal slot, [[Environment]], set when the function is created: it points to the lexical environment (the record of variables) that was current at that moment. When the function is later called, a new environment is created for the call, whose outer link is that saved [[Environment]]. Name lookup then walks: the call's own variables, then the captured environment, then outward through the scope chain.

An environment record is an ordinary heap object. As long as some function's [[Environment]] points to it, the garbage collector considers it reachable, so its variables survive the outer call's return. That is all a closure is: a function plus a reference to the environment it was created in.

V8 optimizes this. When parsing, it determines which variables are referenced by inner functions; only those are placed in a heap-allocated Context object, while the rest live in fast registers and disappear when the call ends. Several closures created in the same call share one Context, which is why they share state. One historical gotcha: if two inner functions share a Context and only one is kept, the Context (and variables used only by the other function) can stay alive, so avoid capturing large data in scopes that also create long-lived callbacks.

Interview Corner

What is a closure?

A function bundled with references to the variables of the lexical scope in which it was created. Because the function keeps a link to that environment, it can read and update those variables after the outer function has returned. Every function in JavaScript is a closure over its defining scope.

Why does a for loop with var print the final value in every callback?

All callbacks close over the same function-scoped var binding, which holds its final value by the time they run. let in a loop head creates a new binding per iteration, so each closure captures a separate variable. Before ES2015, an IIFE per iteration was used.

Give practical uses of closures.

Private state (module pattern, counters), function factories (makeLateFee(2)), memoization caches, once, debounce and throttle, event handlers and timers that remember their data, and partial application.

What does this print?

Show solution
puzzle.js▶ Try it
function make() {
  let n = 0;
  return [() => ++n, () => n];
}
const [inc, get] = make();
const [inc2] = make();
inc(); inc(); inc2();
console.log(get());
Output
2

inc and get share the n from the first call; inc2 has its own n from the second call.

Practice

Challenge: Write rateLimiter(max) that returns a function allow(), which returns true for the first max calls and false afterwards, with a reset() method on the returned function.

Show solution
rate-limiter.js▶ Try it
function rateLimiter(max) {
  let used = 0;
  function allow() {
    if (used >= max) return false;
    used++;
    return true;
  }
  allow.reset = () => { used = 0; };
  return allow;
}
 
const allow = rateLimiter(2);
console.log(allow(), allow(), allow());
allow.reset();
console.log(allow());
Output
true true false
true

Quick check: Closures

3 questions
1What does a closure capture?
2Two functions are returned from the same call of a factory. What do they share?
3Why can a long-lived closure cause memory to stay in use?

Key Takeaways

UseShape
Factoryconst f = make(config); f(x)
Private statelet x; return { get: () => x, set: (v) => { x = v; } }
Remembered data in a callbacksetTimeout(() => use(student), ms)
Fixing the loop bugfor (let i = ...)

Was this tutorial helpful?

Lesson 92 of 139