跪拜 Guibai
← Back to the summary

JavaScript Closures: How the Scope Chain and return Keep Variables Alive

Understanding JavaScript Scope Chain, return and Closures

Introduction

Earlier we learned about pre-compilation, AO/GO, execution context, and the V8 call stack. The scope chain and closures are core concepts built on top of these mechanisms. Many people cannot distinguish the lookup rules of the scope chain, nor do they understand how closures actually retain variables. This article follows the logic of execution context to connect the scope chain, return, and closures.

1. Scope Chain

When V8 executes a function, it creates a corresponding execution context. Each execution context has an outer pointer that points to the outer execution context.

Variable lookup rules: When looking up a variable, the current execution context is searched first; if not found, the lookup proceeds up the outer pointer layer by layer until the global execution context. If it is still not found after reaching the global context, a global variable is automatically created in non-strict mode, while strict mode throws a reference error.

This lookup chain connected by the outer pointer is the scope chain.

Example:

var a = 10
function outer() {
    var b = 20
    function inner() {
        var c = 30
        console.log(a, b, c)
    }
    inner()
}
outer()

Lookup process:

  1. Looking up c: found directly in inner's execution context
  2. Looking up b: not found in inner's context, found in outer's execution context via outer
  3. Looking up a: not found in outer's context, found in the global execution context via outer

Note: The scope chain is determined at the lexical level, based on the position in the code, and is independent of where the function is called.

2. return: Returning an Inner Function to the Outside

The most common way to form a closure is to use return to expose an inner function to the outside. Normally, when a function finishes executing, its execution context is popped off the stack and destroyed, and the inner variables are released. However, if a function defines another function inside and returns that inner function, the situation is different.

function A() {
    var num = 100
    function B() {
        console.log(num)
    }
    return B
}
const fn = A()
fn()

Execution flow:

  1. Call A(), create A's execution context, AO has variable num
  2. Inner function B is returned and assigned to global variable fn
  3. A finishes executing, and its execution context should be destroyed
  4. But B still holds a reference to the inner variable num, so the related variables are not collected

3. Closures

In JavaScript, lexical scoping rules apply: an inner function can always access the variables of the outer function. When function A contains function B, and B is called outside A, even if A has already finished executing, its execution context is not completely destroyed; the variables referenced by B are retained. This set of variables is a closure.

In one sentence: Closure = inner function + the outer variables it captures.

Advantages of Closures

  1. Extend variable lifetime: variables can still be accessed after the outer function finishes
  2. Encapsulate private variables: external code cannot directly access function internals, only through the inner function

Disadvantages of Closures

Memory leaks are likely: as long as the closure is alive, the captured variables will not be garbage collected; if closures are heavily misused and references are not released for a long time, memory usage continues to grow.

Core Conditions for a Closure (all three must be met)

  1. Function nesting, with the inner function referencing the outer function's variables
  2. The inner function is exposed to an outer scope (via return, assignment to a global variable, etc.)
  3. The inner function executes outside

4. Complete Example: Combining Scope Chain, return, and Closures

function counter() {
    let count = 0
    function add() {
        count++
        console.log(count)
    }
    return add
}
const addFn = counter()
addFn() // 1
addFn() // 2
addFn() // 3

Analysis:

  1. counter executes, creating an execution context with count = 0
  2. Inner function add is returned and assigned to global addFn
  3. counter finishes, but since add references count, a closure is formed, and count persists
  4. Each call to addFn uses the scope chain to find count in the closure, achieving accumulation

Key point: count is not global; external code cannot directly modify count, only through the add function. This is encapsulation of a private variable.

5. Common Questions

  1. Is any function nesting a closure? No. Only when an inner function is called outside and references outer variables does a closure form. If the inner function is only called internally, the outer function's execution context is destroyed normally, and no closure exists.
  2. What is the relationship between the scope chain and closures? Closures rely on the scope chain. The variables retained by a closure are the variables in the outer contexts along the scope chain; because of the outer pointer lookup mechanism, inner functions can access variables across scopes.
  3. How can memory leaks caused by closures be avoided? When the closure is no longer needed, manually break the reference: addFn = null, so the garbage collector can reclaim the captured variables.

Summary

  1. Scope chain: each execution context has an outer pointer, variables are looked up along outer until the global context; it is determined by the writing position (lexical scope).
  2. return: a common way to expose inner functions to an outer scope, serving as the bridge to form closures.
  3. Closures: inner functions reference outer variables and execute outside the outer function; advantages are private variable encapsulation and extended variable lifetime; the disadvantage is that improper use can cause memory leaks.