Inside JavaScript Closures: Scope Chain, outer Pointer, and Why Variables Survive
Following the scope chain and the outer pointer: understand the underlying logic of closures in one pass
Preface
Many students, when learning closures, memorize a bunch of definitions but still cannot figure out: What is the relationship between closures and the scope chain? Why can variables inside function A still be accessed after A has finished executing? What gives closures the ability to extend variable lifetime?
Many tutorials present closures as a standalone topic, which makes it easy to think closures are an independent, special piece of syntax. But in fact, closures are a natural result of lexical scoping plus the scope chain, and they belong to the same system as precompilation, AO, and the call stack discussed in the previous article. From the V8 perspective, this article follows the scope chain and breaks down closures step by step: principle, use cases, and pitfalls.
1. Scope Chain (the underlying rules of variable lookup)
- Each execution context (AO/GO) carries an outer pointer. This pointer is determined when the function is defined, not when it is called. It points to the outer scope corresponding to where the function is written.
- Variable lookup process: first look in the current AO; if not found, follow outer to the upper AO/GO and continue; continue until GO, and if still not found, report 'is not defined'. The chain-shaped lookup path strung together by outer is the scope chain.
Example:
// Demo: the outer pointer is determined by the definition position, not the call position
function outer() {
let a = 100
var b = 20
function inner() {
var c = 50
console.log(a,b,c)
}
inner()
}
let a = 200
outer()
- Function inner is defined inside outer, so inner's outer pointer is fixed to point to outer's scope at definition time; it has nothing to do with where inner is called. outer's outer pointer points to the global scope.
- When
fn()is executed, inner's execution context is created. It first looks for variablesa, b, cin inner's AO, finds c and getsc = 50; it cannot find a and b, so it follows the outer pointer to outer's AO and getsa = 100, b = 20. At this point, although the GO pointed to by outer's outer pointer still containsa = 200, the scope chain does not prefer the global scope, because the outer pointer locks the outer scope at the writing position. So the output is 100 20 50.
2. Closure
What is a closure
Background: As we know, after an ordinary function finishes executing, its execution context AO is popped from the call stack, local variables lose their references, and are destroyed by the garbage collector (GC). Closures are the special case that breaks this normal flow.
Basic prerequisite: lexical scoping Function B is defined inside A. At authoring time, B's outer pointer is already bound to A's scope, so B naturally has permission to access variables inside A. This is the underlying basis for closures being able to access outer variables; it is not an extra capability granted by closures.
Core trigger condition: the inner function is taken out of the outer function Simply defining B inside A and calling B inside A does not create a closure. In that scenario, after A finishes executing, B also finishes executing, and no external reference continues to hold B. A's AO pops out and is destroyed normally, and local variables are reclaimed directly; there is no difference from an ordinary function. Only when B leaves A's execution environment by being returned, assigned to a global variable, passed as a callback, and so on, and is called outside A, is the closure activated.
The anomaly When A finishes executing, its AO should normally pop from the call stack and be destroyed as a whole. But because a global variable still holds a reference to B, and B's outer pointer points to A's scope, B depends on variables inside A to run normally. V8 detects that some of A's variables are still being continuously referenced and cannot be reclaimed directly. So A's execution context is not destroyed as a whole; only the variables used by B are kept separately, forming this independent variable set, which is the closure.
Example:
// Standard closure demo: the inner function is returned and called outside
function A() {
let num = 10
function B() {
console.log(num)
num++
}
return B
}
const funcB = A()
funcB()
funcB()
funcB()
- Executing
A()creates A's AO, pushes it onto the call stack, and registers the variable num and function B in the AO. - When A reaches return, it returns function B and assigns it to the global variable
funcB. At this point A's code has finished executing, and its AO is ready to pop. - However, the global variable
funcBholds a reference to B, B's outer pointer points to A's scope, and B depends on the variable num. V8 determines that num still has a valid reference, so A's AO cannot be destroyed entirely; num is retained, and the closure is formed. - Every subsequent call to
funcB()follows B's outer pointer and accesses the num saved in the closure, then modifies its value. So the output is:
10
11
12
Let's also look at a comparison snippet to intuitively see the scenario without a closure:
function A() {
let num = 10
function B() {
console.log(num)
}
B() // Only called inside A; B is not taken out of A
}
A()
A()
B is only called inside A. After A finishes executing, no external variable holds B. A's AO pops from the call stack normally, and num is reclaimed directly. Calling A twice creates a fresh AO and a fresh num each time; they do not affect each other, so the two outputs are both 10. There is no closure. So the output is:
10
10
Advantages and disadvantages of closures
Advantages
- Extending variable lifetime: An ordinary local variable is destroyed after the outer function finishes executing. A closure allows a variable to leave the outer function's execution lifecycle and stay in memory for a long time, so subsequent calls to the inner function can continue to read and write the same variable. A counter is the most typical application.
- Encapsulating private variables: A closure is the classic way to implement private data. The variable is defined in the outer function, so the global scope cannot directly access or change it; it can only be manipulated through the methods we intentionally expose. This avoids global variable pollution and controls read/write access to data.
Example:
function makeAdd() {
let n = 1
return function () {
n++
console.log(n)
}
}
const add = makeAdd()
add()
add()
add()
- After
makeAddfinishes executing, the local variablenshould logically be destroyed; - Because the inner function is returned and assigned to the global
add, a closure is formed andnis retained; - Each call to
add()operates on the samen.
At this point, direct access to n from outside is impossible:
console.log(n) // Uncaught ReferenceError: n is not defined
Disadvantages
It can easily cause memory leaks: a closure itself is not a memory leak; it is unreasonable use of closures that causes leaks. As long as a closure's reference still exists, the captured variables will not be reclaimed. If a long-idle closure is not manually released, the data it holds occupies heap memory for a long time, memory usage keeps rising, and a memory leak forms.
How to prevent memory leaks, example:
function makeAdd() {
let n = 1
return function () {
n++
console.log(n)
}
}
const add = makeAdd()
add()
// No longer need the closure: break the reference, reclaim
add = null
After add = null, no variable holds the inner function, the closure's reference chain is broken, and variable n can be garbage collected, avoiding continuous memory occupation.
Summary
Every execution context has an outer pointer, and these pointers form the scope chain used to look up variables upward. When an inner function is taken outside the outer function and called there, a closure is formed: it keeps outer variables alive, extends their lifetime, and implements private encapsulation. The cost is that improper use can easily cause memory leaks.
Top 1 from juejin.cn, machine-translated. The original thread is authoritative.
Using the outer pointer to explain closures is the right approach — you can see at a glance where variables are being looked up. The moment the setTimeout loop example appears, the beginner confusion basically dissipates.