Skip to content
Velloreth
Programming 8 min read

Closures Explained: How Functions Remember Scope

A closure is a function that remembers the variables where it was created. Learn how they work, the classic loop bug, and where they are useful.

By

What a closure is

A closure is a function together with the variables from the scope where it was defined. The function can read and write those variables even after the outer function has returned.

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

const counter = makeCounter();
counter(); // 1
counter(); // 2
counter(); // 3

makeCounter has returned. Its local variable count should be gone. But the returned function still has access to it, and each call increments the same count.

That is a closure. The function closed over count.

Closures are automatic

There is no closure keyword. Closures arise whenever a function is created inside another function and references the outer function’s variables.

function outer() {
  const message = 'hello';
  function inner() {
    console.log(message); // inner closes over message
  }
  return inner;
}

inner references message, which is not its own variable and not a global. It is a variable from the enclosing scope, so inner captures it. That capture is the closure.

Every function in JavaScript is technically a closure over its lexical scope, even if it captures nothing. The term is usually reserved for the cases where the capture is observable — where the outer scope has returned and the variables are still alive.

The classic loop bug

This is the closure question that appears in every interview, and it is worth understanding properly.

for (var i = 0; i < 3; i++) {
  setTimeout(() => console.log(i), 0);
}
// 3
// 3
// 3

The output is three 3s, not 0, 1, 2. Why?

var is function-scoped, not block-scoped. There is only one i for the entire loop. All three callbacks close over that same variable. By the time the timers fire, the loop has finished and i is 3.

The fix is let, which is block-scoped and creates a new binding per iteration:

for (let i = 0; i < 3; i++) {
  setTimeout(() => console.log(i), 0);
}
// 0
// 1
// 2

Each iteration gets its own i, so each callback captures a different variable.

The older workaround was an immediately-invoked function expression, which created a new scope per iteration:

for (var i = 0; i < 3; i++) {
  (function (j) {
    setTimeout(() => console.log(j), 0);
  })(i);
}

You will see this pattern in older code. let makes it unnecessary.

What closures are for

Data privacy

Closures create variables that are accessible only through the functions that capture them.

function createBankAccount(initial) {
  let balance = initial; // private

  return {
    deposit(amount) {
      if (amount <= 0) throw new Error('Invalid amount');
      balance += amount;
      return balance;
    },
    withdraw(amount) {
      if (amount > balance) throw new Error('Insufficient funds');
      balance -= amount;
      return balance;
    },
    getBalance() {
      return balance;
    },
  };
}

const account = createBankAccount(100);
account.deposit(50);   // 150
account.balance;       // undefined — not accessible

balance cannot be read or written from outside. The only way in is through the returned methods, which enforce the rules. This is the module pattern, and it predates ES modules.

Function factories

function greeter(greeting) {
  return (name) => `${greeting}, ${name}!`;
}

const hello = greeter('Hello');
const hi = greeter('Hi');

hello('Ada'); // 'Hello, Ada!'
hi('Ada');    // 'Hi, Ada!'

Each returned function remembers its own greeting.

Memoisation

function memoize(fn) {
  const cache = new Map();
  return function (...args) {
    const key = JSON.stringify(args);
    if (cache.has(key)) return cache.get(key);
    const result = fn.apply(this, args);
    cache.set(key, result);
    return result;
  };
}

const slowSquare = (n) => { /* expensive */ return n * n; };
const fastSquare = memoize(slowSquare);

The cache lives in the closure. It is invisible to callers and persists between calls.

Event handlers with context

function attachHandlers(items) {
  return items.map((item) => () => {
    console.log(`Clicked ${item.name}`); // captures item
  });
}

Each handler remembers its own item, which is why you can generate handlers in a loop without the loop bug — as long as you use let or a function parameter.

Once-only initialisation

function once(fn) {
  let called = false;
  let result;
  return function (...args) {
    if (!called) {
      called = true;
      result = fn.apply(this, args);
    }
    return result;
  };
}

The called flag lives in the closure, so the wrapped function runs at most once.

Closures and memory

A closure keeps its captured variables alive. That is the point, but it has a consequence: memory is retained as long as the closure exists.

function processData() {
  const hugeArray = new Array(1_000_000).fill(0);
  return function () {
    return hugeArray.length; // captures the whole array
  };
}

The returned function only needs the length, but it captures the entire array, which stays in memory for as long as the function does.

The fix is to capture only what you need:

function processData() {
  const hugeArray = new Array(1_000_000).fill(0);
  const length = hugeArray.length; // capture the number, not the array
  return function () {
    return length;
  };
}

This is not a leak in the strict sense — the memory is reachable and will be freed when the closure is. But it is a common source of unexpectedly high memory use, especially in long-lived event handlers.

Closures in other languages

Python has closures, with a wrinkle: you cannot rebind an outer variable without nonlocal.

def make_counter():
    count = 0
    def counter():
        nonlocal count
        count += 1
        return count
    return counter

Go closures capture variables by reference, which produces the same loop bug as JavaScript’s var:

for i := 0; i < 3; i++ {
    go func() { fmt.Println(i) }() // may print 3, 3, 3
}

Go 1.22 changed loop variable semantics to create a new variable per iteration, fixing this.

Rust closures capture by reference, mutable reference, or move, and the compiler enforces the rules. The move keyword forces capture by value, which is required when the closure outlives the scope.

Java requires captured variables to be effectively final, which sidesteps the loop bug entirely.

Closures and the module pattern

Before ES modules existed, closures were how JavaScript code was organised into private units. The pattern is still worth knowing because it appears in a great deal of existing code, and because it explains why module systems work the way they do.

const Counter = (function () {
  let count = 0; // private to this closure

  function increment() {
    count++;
    return count;
  }

  function reset() {
    count = 0;
  }

  return { increment, reset }; // only these are exposed
})();

Counter.increment(); // 1
Counter.increment(); // 2
Counter.count;       // undefined — not exposed

The immediately-invoked function expression creates a scope, runs once, and returns an object holding the functions that close over count. Nothing outside can reach count except through the exposed methods.

ES modules give you the same privacy with cleaner syntax — anything not exported is private to the module — but the underlying mechanism is still a closure over the module scope.

Closures and the this binding

A subtle interaction worth knowing: closures capture variables, but this is not a variable. It is determined by how a function is called, not where it is defined.

const timer = {
  seconds: 0,
  start() {
    setInterval(function () {
      this.seconds++; // `this` is not the timer object
    }, 1000);
  },
};

The inner function is called by setInterval, so this is the global object (or undefined in strict mode), not timer. The fix is an arrow function, which does not have its own this and inherits it from the enclosing scope:

start() {
  setInterval(() => {
    this.seconds++; // `this` is the timer object
  }, 1000);
}

The older workaround was capturing this in a variable:

start() {
  const self = this;
  setInterval(function () {
    self.seconds++;
  }, 1000);
}

You will see const self = this and const that = this in older codebases. Arrow functions make it unnecessary, but recognising the pattern helps when reading legacy code.

Practical guidance

  • Use let or const in loops, never var, when creating closures.
  • Capture only what you need to avoid retaining large objects.
  • Use closures for privacy instead of underscore-prefixed conventions.
  • Be careful with long-lived handlers — they keep their captured scope alive.
  • Remember that closures capture variables, not values — the variable’s current value is read when the function runs, not when it is created.
  • Use once and memoize patterns rather than hand-rolling flags and caches.

For the related concepts, see higher-order functions explained and pure functions and side effects. For how closures enable state management, immutability explained and dependency injection without a framework.

Quotable summary

A closure is a function bundled with the variables from the scope where it was defined, so it can use them after that scope has returned. Closures arise automatically whenever a function is created inside another and references its variables; there is no special syntax. The classic loop bug occurs because var is function-scoped, so all callbacks share one variable, while let creates a new binding per iteration. Closures enable data privacy, function factories, memoisation, and event handlers with context, and they are the mechanism behind the module pattern. They keep captured variables alive, so capturing a large object unnecessarily retains memory for as long as the closure exists.

Frequently asked questions

What is a closure in simple terms?
A closure is a function that remembers the variables from where it was created, even after that outer function has finished running. It is like a function carrying a backpack of the values it needs.
Why do closures exist?
Because functions in most languages capture their surrounding scope. This lets you create functions that carry state without using global variables, which is the basis of data privacy, function factories, and callbacks that remember context.
What is the classic closure bug in a loop?
Using var in a for loop with callbacks. Because var is function-scoped, all the callbacks share one variable, so they all see the final value. Using let creates a new binding per iteration, so each callback sees its own value.
Do closures cause memory leaks?
They can retain memory, because a captured variable stays alive as long as the closure does. This is not a leak in the strict sense, but capturing a large object unnecessarily keeps it in memory. Release the closure when you no longer need it.
What is the difference between a closure and a scope?
A scope is the region of code where a variable is accessible. A closure is a function plus the scope it captured. The scope exists while the code runs; the closure keeps that scope alive afterwards.
Are closures used in languages other than JavaScript?
Yes. Python, Ruby, Swift, Kotlin, Go, Rust, C#, and most modern languages have closures. C does not have them natively, though function pointers and structs can approximate them.