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
outerpointer 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:
- Looking up
c: found directly in inner's execution context - Looking up
b: not found in inner's context, found in outer's execution context via outer - 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:
- Call
A(), create A's execution context, AO has variablenum - Inner function B is returned and assigned to global variable
fn Afinishes executing, and its execution context should be destroyed- 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
- Extend variable lifetime: variables can still be accessed after the outer function finishes
- 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)
- Function nesting, with the inner function referencing the outer function's variables
- The inner function is exposed to an outer scope (via return, assignment to a global variable, etc.)
- 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:
counterexecutes, creating an execution context withcount = 0- Inner function
addis returned and assigned to globaladdFn - counter finishes, but since
addreferencescount, a closure is formed, and count persists - Each call to
addFnuses the scope chain to findcountin the closure, achieving accumulation
Key point:
countis not global; external code cannot directly modifycount, only through theaddfunction. This is encapsulation of a private variable.
5. Common Questions
- 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.
- 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
outerpointer lookup mechanism, inner functions can access variables across scopes. - 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
- Scope chain: each execution context has an
outerpointer, variables are looked up alongouteruntil the global context; it is determined by the writing position (lexical scope). - return: a common way to expose inner functions to an outer scope, serving as the bridge to form closures.
- 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.