Skip to content

Closures

Functions that retain access to their lexical scope, enabling private state and factories.

What you'll learn

  • What a closure is and how the lexical scope is preserved
  • Creating private variables with closures
  • Factory functions and partial application
  • Memoization with closures for caching
  • Common pitfalls: closures in loops and memory considerations

Concept

The Core Idea

A closure is the combination of a function and the lexical environment in which it was created. When an inner function is returned from an outer function, it carries a reference to the outer function's variables — even after the outer function has finished executing. The variables are not copied; they are kept alive by the closure's reference to them.

This is a natural consequence of lexical scoping, not a special feature. Every function in JavaScript is technically a closure over its surrounding scope. The pattern becomes visible when you deliberately return a function that uses variables from an outer scope.

Private State

Closures are the traditional way to create private variables in JavaScript. By declaring a variable inside a factory function and returning methods that read or write it, you hide the variable from the outside. Only the returned functions can access it. This is the module pattern and the basis of encapsulation before private class fields existed.

Factory Functions and Partial Application

A closure can capture arguments and produce a new, specialized function. makeAdder(10) returns a function that adds 10 to whatever you pass it. This is partial application — fixing some arguments now and supplying the rest later. It is the foundation of currying and many functional utilities.

Memoization

Closures can cache expensive results. A memoized function stores a map of inputs to outputs in its closure. On subsequent calls with the same input, it returns the cached value instead of recomputing. This trades memory for speed and is a classic optimization for pure functions.

The Loop Pitfall

A famous historical bug involved closures in loops with var. Because var is function-scoped, all closures in the loop shared the same variable, which ended at its final value. let fixes this by creating a fresh binding per iteration. Always use let (or const) in loops that create closures.

Example

              // Private state with a closure — the balance is hidden
function createAccount(initialBalance) {
  let balance = initialBalance;
  return {
    deposit(amount) {
      balance += amount;
      return balance;
    },
    withdraw(amount) {
      if (amount > balance) throw new Error("Insufficient funds");
      balance -= amount;
      return balance;
    },
    getBalance() {
      return balance;
    },
  };
}
const account = createAccount(100);
account.deposit(50);
console.log(account.getBalance()); // 150
// console.log(balance); // ReferenceError — balance is private

// Factory / partial application
const multiply = (a) => (b) => a * b;
const double = multiply(2);
const triple = multiply(3);
console.log(double(5), triple(5)); // 10 15

// Memoization with a closure
function memoize(fn) {
  const cache = new Map();
  return (arg) => {
    if (cache.has(arg)) return cache.get(arg);
    const result = fn(arg);
    cache.set(arg, result);
    return result;
  };
}
const slowSquare = memoize((n) => {
  console.log("computing for", n);
  return n * n;
});
console.log(slowSquare(4)); // computes
console.log(slowSquare(4)); // cached — no "computing" log
            

Demonstrates private state (a bank account with hidden balance), a partial-application factory (multiply), and a memoize higher-order function that caches results in its closure.

Try it

  • Math Evaluator

    Closures often wrap math — evaluate the inner computations live.

  • JSON Formatter

    Inspect the cached data structures closures maintain.

Common mistakes

The mistake

Creating closures in a loop with var and sharing one variable

The fix

var is function-scoped, so every closure shares the same variable. Use let (or const) in the loop, which creates a fresh binding per iteration and gives each closure its own value.

The mistake

Accidentally keeping large objects alive through closures (memory leak)

The fix

A closure holds a reference to its entire scope. If you capture a large object, it cannot be garbage-collected. Release references by setting them to null or narrowing the closure to only what it needs.

Related Cheatsheets

Look up unfamiliar terms

A beginner-friendly glossary explains jargon in plain English — variables, functions, DOM, Promise, and more.

View glossary

Build real projects

Apply what you learned by building guided projects with starter code and solutions.

View projects

Decode error messages

Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.

View errors