Back to series
· 8 min read

Closure


I. What Is a Closure

A closure is a function mechanism found in programming languages, usually composed of two parts:

  1. Function object (Function): contains the executable code logic.
  2. Lexical environment (Lexical Environment): stores the external variables that were accessible when the function was defined, along with their bindings.

Simply put, a closure is a function that can remember variables from an outer scope.

1.1 The Difference Between an Ordinary Function and a Closure

First, look at an ordinary function:

function greet() {
    const message = "Hello";
    console.log(message);
}

greet();

message is a local variable inside the function. After the function finishes executing, it no longer needs to be retained, provided there are no other references to it.

Now look at a closure:

function createGreeter() {
    const message = "Hello";

    return function greet() {
        console.log(message);
    };
}

const greet = createGreeter();

greet(); // Hello

An important phenomenon occurs here:

  • message is defined inside createGreeter.
  • The inner function greet references message.
  • createGreeter has already finished executing.
  • The outside world can still access message through the returned function.

This is the core characteristic of a closure: a function can continue to access variables in its lexical environment from outside the scope in which it was originally defined.

1.2 The Basic Structure of a Closure

flowchart TD
    A["Call the outer function createGreeter"] --> B["Create the local variable message"]
    B --> C["Define the inner function greet"]
    C --> D["The inner function references message"]
    D --> E["Return the inner function"]
    E --> F["The outer function finishes executing"]
    F --> G["The outside world keeps a reference to the function"]
    G --> H["Call greet"]
    H --> I["Access message in the original lexical environment"]

    style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
    style B fill:#E5F4EC,stroke:#A3CBB5,color:#334155
    style C fill:#F3EDFC,stroke:#C4B2E3,color:#334155
    style D fill:#FFF5DE,stroke:#E8D29A,color:#334155
    style E fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
    style F fill:#E8EDF2,stroke:#B8C3CE,color:#334155
    style G fill:#E5F4EC,stroke:#A3CBB5,color:#334155
    style H fill:#F3EDFC,stroke:#C4B2E3,color:#334155
    style I fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
    linkStyle default stroke:#A3B8AC,stroke-width:1.5px

II. The Conditions for Forming a Closure

The formation of a closure usually involves three key conditions:

  1. There is a nested function, that is, another function is defined inside a function.
  2. The inner function references a variable in the scope of the outer function.
  3. The inner function can still be accessed or executed after the outer scope has ended.

For example:

function outer() {
    let count = 0;

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

    return inner;
}

const counter = outer();

console.log(counter()); // 1
console.log(counter()); // 2
console.log(counter()); // 3

inner references count in outer, and can still access it after outer has finished executing.

Note that the concrete implementation of closures depends on the language. JavaScript, Python, and other languages have different mechanisms for closure objects, variable binding, and scope implementation, so the implementation details of one language cannot be treated as a universal rule for all languages.

III. The Underlying Principle of Closures: Lexical Scope

To understand closures, you first need to understand lexical scope (Lexical Scope).

Lexical scope, also called static scope (Static Scope), means that the accessible range of a variable is determined by the nesting structure at the time the code is defined, rather than by where the function is actually called.

3.1 Lexical Scope

const name = "Global";

function outer() {
    const name = "Outer";

    function inner() {
        console.log(name);
    }

    return inner;
}

const fn = outer();

fn(); // Outer

Although inner is called in the global scope, it can still access name from the outer scope in which it was defined.

The reason is:

  • inner is defined inside outer.
  • The lexical outer environment of inner is the environment of outer.
  • Variable lookup proceeds according to the lexical environment relationships at definition time.

3.2 Scope Chain

When a function accesses a variable, the runtime needs to look up that variable according to scope rules.

This can usually be abstracted as:

flowchart TD
    A["Function accesses a variable"] --> B{"Does the variable exist in the current scope?"}
    B -->|"Yes"| C["Read the variable from the current scope"]
    B -->|"No"| D["Look up the outer lexical environment"]
    D --> E{"Does the variable exist in the outer environment?"}
    E -->|"Yes"| F["Read the variable from the outer environment"]
    E -->|"No"| G["Continue searching upward"]
    G --> H{"Has the global environment been reached?"}
    H -->|"No"| D
    H -->|"Yes"| I["Variable is undefined or cannot be resolved"]

    style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
    style B fill:#FFF5DE,stroke:#E8D29A,color:#334155
    style C fill:#E5F4EC,stroke:#A3CBB5,color:#334155
    style D fill:#F3EDFC,stroke:#C4B2E3,color:#334155
    style E fill:#FFF5DE,stroke:#E8D29A,color:#334155
    style F fill:#E5F4EC,stroke:#A3CBB5,color:#334155
    style G fill:#F3EDFC,stroke:#C4B2E3,color:#334155
    style H fill:#FFF5DE,stroke:#E8D29A,color:#334155
    style I fill:#E8EDF2,stroke:#B8C3CE,color:#334155
    linkStyle default stroke:#A3B8AC,stroke-width:1.5px

The scope chain determines which variables a function can access.

Closures, in turn, allow a function to still access the lexical bindings it needs to retain even when the original defining environment is no longer maintained by the ordinary call stack.

IV. The Relationship Between Closures and Execution Contexts

This is an important part of understanding the underlying mechanism of closures.

In JavaScript, a function call creates an execution context. The execution context contains the information needed to execute the current code, while the lexical environment is responsible for supporting variable binding and scope lookup.

4.1 Execution Context

When a function executes, the runtime needs to manage:

  • The parameters of the current function.
  • Local variables.
  • The lexical environment.
  • A reference to the outer environment.
  • Execution-related information such as this.

When a function finishes executing, its execution context exits the execution process.

However, this does not mean that all related variables must be destroyed immediately.

4.2 Why Local Variables Do Not Disappear

For example:

function createCounter() {
    let count = 0;

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

const counter = createCounter();

After createCounter finishes executing:

  • The outer function has already returned.
  • The inner function is still referenced by counter.
  • The inner function still needs to access count.
  • Therefore, the runtime must retain the lexical environment information needed for the inner function's access.

This can be abstracted as:

flowchart TD
    A["Execute createCounter"] --> B["Create lexical environment"]
    B --> C["Create count = 0"]
    C --> D["Create inner function"]
    D --> E["Inner function references count"]
    E --> F["Return inner function"]
    F --> G["Outer execution ends"]
    G --> H["Inner function is still referenced"]
    H --> I["Retain required lexical environment"]
    I --> J["Subsequent calls continue accessing count"]

    style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
    style B fill:#F3EDFC,stroke:#C4B2E3,color:#334155
    style C fill:#E5F4EC,stroke:#A3CBB5,color:#334155
    style D fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
    style E fill:#FFF5DE,stroke:#E8D29A,color:#334155
    style F fill:#E5F4EC,stroke:#A3CBB5,color:#334155
    style G fill:#E8EDF2,stroke:#B8C3CE,color:#334155
    style H fill:#F3EDFC,stroke:#C4B2E3,color:#334155
    style I fill:#FFF5DE,stroke:#E8D29A,color:#334155
    style J fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
    linkStyle default stroke:#A3B8AC,stroke-width:1.5px

4.3 A closure does not mean the entire function call stack is retained

This is an easy point to misunderstand.

A closure does not mean that the entire execution context and call stack frame of the outer function must persist.

More precisely:

  • The outer function call has already ended.
  • The outer function's call stack frame can usually be released.
  • The lexical bindings that the inner function needs to access are still retained.
  • The runtime can store this information through heap objects, environment records, or other internal structures.

In JavaScript engines, exactly how closure environments are represented and optimized is an implementation detail.

Therefore, you cannot simply think of a closure as “putting the function stack frame on the heap”.

V. Variable Capture Mechanisms of Closures

The most critical capability of a closure is capturing variables from an outer scope.

Different languages differ in their capture methods. Common cases include:

  • Capturing the variable itself.
  • Capturing a copy of the variable's current value.
  • Capturing an object reference.
  • Specifying the capture method through explicit declaration.

5.1 JavaScript: Capturing variable bindings

function createCounter() {
    let count = 0;

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

const counter = createCounter();

console.log(counter()); // 1
console.log(counter()); // 2
console.log(counter()); // 3

A closure accesses the count binding in the outer lexical environment.

Each call modifies the same binding, so the state can continue to accumulate.

5.2 Multiple closures share the same variable

function createActions() {
    let count = 0;

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

        decrement() {
            count--;
        },

        getValue() {
            return count;
        }
    };
}

const actions = createActions();

actions.increment();
actions.increment();
actions.decrement();

console.log(actions.getValue()); // 1

All three inner functions access the same count variable.

They share the variable binding in the same lexical environment, rather than each creating an independent count.

5.3 Each call creates an independent closure environment

function createCounter() {
    let count = 0;

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

const counterA = createCounter();
const counterB = createCounter();

console.log(counterA()); // 1
console.log(counterA()); // 2

console.log(counterB()); // 1
console.log(counterB()); // 2

Each call to createCounter creates a new local variable binding.

Therefore:

  • counterA accesses its own count.
  • counterB accesses another copy of count.
  • The state of the two closures is independent of each other.

6. Closures and Variable Lifetime

Ordinary local variables are usually no longer needed after the function call ends, but variables referenced by closures may continue to live.

6.1 Ordinary Local Variables

function normal() {
    let value = 100;
    console.log(value);
}

normal();

If there are no other references, after normal finishes executing, the data related to the local variables no longer needs to be retained.

6.2 Variables Referenced by Closures

function createFunction() {
    let value = 100;

    return function () {
        return value;
    };
}

const fn = createFunction();

console.log(fn()); // 100

Even after the outer function has finished executing, value still needs to be retained because the inner function will still access it.

6.3 Lifetime of Closure Variables

This can be understood in terms of reference relationships:

flowchart TD
    A["Create outer function environment"] --> B["Create local variable"]
    B --> C["Inner function captures the variable"]
    C --> D["External code holds a reference to the inner function"]
    D --> E["Closure continues to access the variable"]
    E --> F{"Is there still a valid reference?"}
    F -->|"Yes"| G["Continue retaining the related environment"]
    F -->|"No"| H["Environment and objects become eligible for collection"]
    G --> F

    style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
    style B fill:#E5F4EC,stroke:#A3CBB5,color:#334155
    style C fill:#F3EDFC,stroke:#C4B2E3,color:#334155
    style D fill:#FFF5DE,stroke:#E8D29A,color:#334155
    style E fill:#E5F4EC,stroke:#A3CBB5,color:#334155
    style F fill:#FFF5DE,stroke:#E8D29A,color:#334155
    style G fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
    style H fill:#E8EDF2,stroke:#B8C3CE,color:#334155
    linkStyle default stroke:#A3B8AC,stroke-width:1.5px

Things to note:

  • A closure being reachable does not mean that all outer variables must be retained forever.
  • The engine may retain only the variables that are actually needed.
  • When the closure and its related environment are no longer reachable, the related objects can be garbage-collected.
  • The exact timing of garbage collection is determined by the runtime; you cannot rely on immediate release.

7. Typical Use Cases for Closures

Closures are not only a language feature but also a common software design technique.

7.1 Data Encapsulation and Private State

Closures can keep state inside a function and expose only a limited set of operations.

function createAccount(initialBalance) {
    let balance = initialBalance;

    return {
        deposit(amount) {
            if (amount > 0) {
                balance += amount;
            }
        },

        withdraw(amount) {
            if (amount > 0 && amount <= balance) {
                balance -= amount;
            }
        },

        getBalance() {
            return balance;
        }
    };
}

const account = createAccount(1000);

account.deposit(500);
account.withdraw(200);

console.log(account.getBalance()); // 1300

Here:

  • balance cannot be accessed directly through account.balance.
  • External code can only call the exposed methods.
  • All methods share the same internal state.

This is a closure-based approach to state encapsulation.

7.2 Function Factories

A function factory (Function Factory) refers to creating and returning functions with specific behavior via a function.

function multiplyBy(factor) {
    return function (number) {
        return number * factor;
    };
}

const double = multiplyBy(2);
const triple = multiplyBy(3);

console.log(double(10)); // 20
console.log(triple(10)); // 30

double and triple each capture a different factor value.

Useful for:

  • Parameter pre-configuration.
  • Rule generation.
  • Function customization.
  • Reusable business logic.

7.3 Higher-Order Functions and Callbacks

Closures are often used in combination with higher-order functions.

A higher-order function is a function that takes a function as an argument, or returns a function.

function createHandler(prefix) {
    return function (message) {
        console.log(prefix + message);
    };
}

const infoHandler = createHandler("[INFO] ");
const errorHandler = createHandler("[ERROR] ");

infoHandler("服务启动");
errorHandler("连接失败");

Different callback functions capture different contextual information, so that a single set of execution logic can serve different business scenarios.

7.4 Debouncing and Throttling

Closures are often used to preserve the execution state of a function.

Debouncing (Debounce):