Skip to content
IT glossary
ProgrammingUpdated December 3, 2026

Closure

Замыкание

A function that keeps access to variables from the scope where it was created. It can still use those variables when called elsewhere, even after the function that created it has returned.

What a closure is

A closure is a function together with access to its surrounding lexical environment. That access lets a function use information that wasn't passed in as an argument. For example, you can create a button handler that knows which item to add to a cart even though the browser passes it only a click event, not the item's ID.

How scope and capture work

In JavaScript, a name used inside a function is resolved according to where the function was defined, not where it was called. JavaScript calls this lexical scope. If the function uses a variable from an enclosing scope, it keeps access to that variable. Returning a function is a common way to demonstrate a closure, but it isn't required: passing a function to an event listener can have the same effect.

In JavaScript, the function captures a binding, not a snapshot of its value. Think of a binding as the slot associated with a variable name. If the value in the slot changes, the function reads the new value the next time it uses that variable. Other languages may have different capture rules.

Example: a reader and a writer

function makeCounter() {
  let count = 0;
  return {
    increment: () => ++count,
    read: () => count,
  };
}

const counter = makeCounter();
counter.increment();
console.log(counter.read());       // 1
console.log(makeCounter().read()); // 0

increment and read created by the same call share one count. read doesn't keep the original 0: it sees the change made by increment. A new call to makeCounter creates a separate count, so the second counter starts at zero. Callers can use the returned methods, but they can't access the local variable directly.

Uses and pitfalls

Closures are useful for keeping private state, carrying configuration into a callback, or building specialized functions. For example, a formatting factory can take a locale once and return a function that takes only a number.

A common mistake is to schedule callbacks inside for (var i = 0; i < 3; i++) and expect each callback to remember its iteration number. If the callbacks run after the loop, all three read 3 from the same binding. Declaring i with let in the loop header gives each iteration its own binding. Also watch the lifetime of a callback: a listener that stays registered can keep an object reachable through its closure even after the rest of the program no longer needs it.

In interviews

Expect a short snippet and a question about what it prints. Trace where each variable is declared, which functions share the same binding, and when each read or write happens. That reasoning explains both stateful counters and deferred callbacks.