跪拜 Guibai
← Back to the summary

Scope, Closures, and Objects: How JavaScript Keeps Variables Alive After Functions Return

JavaScript Scope, Closures, and Objects

2026.11.19


Starting with a question

In the code below, what value does console.log(age) actually get?

function outer() {
    var age = 18
    function inner() {
        console.log(age)
    }
    return inner
}
var getAge = outer()
getAge() // ??

When this code runs in a real environment, getAge() outputs 18. When outer finishes executing, common sense suggests its local variable age should become invalid, but it is still retained and accessible. This phenomenon involves three interrelated concepts: scope, closures, and objects.

The article discusses all three in this order.


1. Scope: where variables are visible

1.1 What is scope

Scope is the boundary that controls where variables can be accessed in code. In JavaScript, there are three basic types of scope:

Scope Description Example
Global scope Variables declared outside all functions, accessible anywhere var myname = 'Li Si'
Function scope Variables declared inside a function, accessible only within that function var age = 18 inside outer
Block scope let / const combined with {} statement blocks form an independent scope let a = 2 inside if (true) { let a = 2 }

[!TIP] Difference: var is only constrained by function scope, while let / const are also constrained by block scope.

1.2 Visibility is one-way: inner sees outer

For cross-scope access, there is one rule to remember:

A function can access variables declared outside it; code outside a function cannot access variables declared inside it.

Cases like "can access parameters" and "can access outer variables" are corollaries of this rule: every identifier in a function body first looks itself up in its own scope, and if not found, looks up one level, all the way to the global scope; if still not found, an error is thrown. The lookup direction is from inside out, one-way.

1.3 Scope chain: the order of variable lookup

When the engine executes a function, it creates a corresponding execution context. When looking up a variable, the engine checks along a chain level by level:

  1. Look inside the current execution context;
  2. If not found, follow the outer reference to the next outer execution context;
  3. Until the global execution context; if found, return its value; if not found, return undefined or throw an error.

This chain of outward lookup is the scope chain (Scope Chain).

[!NOTE] Note that this chain is determined at code definition time, not built temporarily when the function is called. This property leads to the next section's "lexical scope".

1.4 Lexical scope: based on definition, not call site

Lexical scope means that variable references in a function body are bound to where the function is defined, not where it is called.

Look at this classic pitfall:

var myname = 'Li Si'

function bar() {
    console.log(myname) // Question: which myname is fetched here?
}

function foo() {
    var myname = 'Zhang San'
    bar() // bar is defined globally, unrelated to foo
}

foo() // Outputs 'Li Si', not 'Zhang San'

Although bar is called inside foo, bar is defined in the global scope, so its myname binds to the global myname ('Li Si'). Variable resolution depends on where the function is defined, not where it is called.

Cheating lexical scope: eval() - eval() can execute strings as code, effectively changing variable resolution at runtime, thus bypassing lexical scope. This approach hurts execution performance and presents security risks, and should be avoided.

1.5 Temporal Dead Zone (TDZ) for block scope

let / const have a trap: accessing a variable before its declaration, even within the same scope, throws an error (not undefined). This is called the temporal dead zone (TDZ, Temporal Dead Zone):

let a = 1
if (true) {
    console.log(a) // ❌ Temporal dead zone: this throws an error, not undefined
    let a = 2
}

Because there is a let a declaration inside the block, from the start of that block to the line of declaration, a is in a dead zone; accessing a in this interval throws an error directly.

1.6 Call stack: execution order of function calls

Function calls rely on a stack - a last-in-first-out (LIFO) data structure. Each call pushes a "frame" (recording local variables and return address) onto the stack; it is popped when the function returns. As calls layer and return, the top of the stack is always the currently executing frame, forming the call stack (Call Stack).

[!NOTE] The call stack and the "scope chain" are two different mechanisms: the call stack manages "how functions return", while the scope chain determines "where variables look up". They should be distinguished.


2. Closures: functions retaining outer variables

2.1 Why closures exist

Back to the question at the beginning. According to lexical scope rules, inner is defined inside outer, so it has access to outer's age. But a key question arises: when outer finishes executing, its execution context should be collected, so does age get destroyed?

JavaScript's approach: when inner is still referenced externally (here by getAge), outer's execution context is not fully collected. The variables referenced by inner (here age) continue to exist as a set in the call stack. This retained set is the closure (Closure).

[!TIP] Think of it as: closure = inner function + the outer variables it references. It allows the inner function to access variables declared in the outer function's scope even after the outer function has finished executing.

2.2 Gains and losses

Content Description
✅ Advantage Extends variable lifetime Variables live as long as the inner function, and remain accessible after the outer function returns
✅ Advantage Encapsulates private variables Variables are not directly exposed, can only be read/written through the interface provided by the inner function
⚠️ Disadvantage Can cause memory leaks Variables captured by closures keep occupying memory without release; if no longer needed after long use, references should be manually set to null to avoid memory retention

2.3 Returning a function: preserving outer variables with the function

This is the most typical closure form - returning an inner function so the outer variables are preserved with it:

function createPrinter() {
    var prefix = 'To print: '
    let suffix = ' (end)'
    function print() {
        console.log(prefix + 'content' + suffix)
    }
    return print
}
var myPrint = createPrinter()
myPrint() // To print: content (end) - createPrinter has finished, but prefix and suffix are still retained

createPrinter returns print, and print references prefix / suffix. So even after createPrinter finishes, these two variables are retained because they are captured by the closure. This is extending variable lifetime. The age in the opening question is accessible for the same reason.

2.4 Encapsulating private variables: read/write only through methods

Another common pattern is returning an object with methods, hiding variables inside a closure, allowing read/write only through methods. External code cannot directly access the variable itself, only the interface methods:

function makeCounter() {
    var count = 0 // Private variable - not directly accessible outside
    return {
        increment: function () { count++ },
        read: function () { return count }
    }
}
var counter = makeCounter()
counter.increment()
console.log(counter.read()) // 1
counter.count // undefined, cannot access this variable externally

The above pattern is how JavaScript implements "private members".

2.5 Persistent state: counter example

Closures not only enable reading, but also allow state to accumulate. Each call to the inner function still modifies the same captured i:

function add(i = 0) {
    i++
    console.log(i)
    return function () {
        i++
        console.log(i)
    }
}
let next = add() // 1
next() // 2
next() // 3
next() // 4

i persists inside the closure. Note: add() is called only once and returns next; after that, next() is called multiple times, each time performing i++ on the same captured i, so the value monotonically increases. This is not a separate copy each time, but the same shared state.

2.6 The var trap: shared variables in loops

var does not have block scope, so when combined with closures in loops, it can cause data-sharing problems:

var arr = []
for (var i = 1; i <= 5; i++) {
    function foo(j) {
        arr.push(function () {
            console.log(j)
        })
    }
    foo(i) // Pass the current value of i as j
}
for (var k = 0; k < arr.length; k++) {
    arr[k]() // 1 2 3 4 5
}

[!NOTE] Why can't we directly write console.log(i)? Because var i is a single variable in the loop; if all functions directly reference i, after the loop ends they all read the same final value 6. Passing the current value as parameter j into foo effectively captures the current i into separate closures in each iteration. This is a common workaround to avoid var variable sharing.

The simpler fix: use let for the loop variable. let i creates an independent i in each iteration, so closures can each capture their own value, also outputting 1 2 3 4 5:

var arr = []
for (let i = 1; i <= 5; i++) {
    arr.push(function () {
        console.log(i)
    })
}
for (let k = 0; k < arr.length; k++) {
    arr[k]() // 1 2 3 4 5
}

(This example also confirms section 1.1: let's block scope makes each iteration's i independent, so they don't affect each other.)

2.7 Block scope + scope chain: nearest lookup and shadowing

Return to the scope chain again, looking at an example mixing function scope, block scope, and variable shadowing:

function bar() {
    var myname = 'Boss Cao' // function scope
    let test1 = 100
    if (1) {
        let myname = 'Student Xing' // block-level same name shadows the myname above
        console.log(test1) // test1? This block doesn't have it, look one level up, find 100 in bar's function scope
    }
}
function foo() {
    var myname = 'Huanghuang'
    { bar() } // bar is defined globally, unrelated to foo
}
var myname = 'Fu Zong'
foo() // Outputs 100

This outputs 100. The block containing console.log(test1) (the if block) does not declare test1, so it looks up the scope chain one level out, finds let test1 = 100 in bar's own function scope, and uses that value - it does not go all the way to the global scope.

This example also includes two details that review the previous sections:


3. Objects: where the rules land

3.1 Everything is an object?

The statement "in JavaScript everything is an object" is not entirely accurate. A more accurate statement: objects are the core structure for organizing data in JS, and functions and arrays are also objects. But there are indeed special "primitive values" that are not objects. First, distinguish:

Primitive types (primitive values): number, string, boolean, null, undefined, symbol, bigint

Reference types (objects): object {}, array [], function(){}

[!NOTE] A property of Symbol: every Symbol created is unique, even if the description is the same, they are not equal.

let a = Symbol('a')
let b = Symbol('a')
console.log(a === b) // false

3.2 Object CRUD

Objects are essentially "key-value" containers. Besides fixed key names, you can also use variables as keys and dynamically add or delete properties:

let obj = { name: 'Zhang San', age: 18 }
obj.girlfriend = 'Li Si' // add
obj.age = 20 // update
delete obj.girlfriend // delete

let key = 'hello'
obj[key] = 'world' // use variable as key to add dynamically
console.log(obj)

3.3 Constructors: creating objects in bulk

Creating each object manually is inefficient, so constructors are introduced - functions called with new, used to create instances with the same structure in bulk:

function Car(color) {
    this.name = 'Benz'
    this.price = 1000000
    this.color = color // initialize with the passed color
    this.engine = 'V82.0'
}
let car1 = new Car('red')
let car2 = new Car('blue')
let car3 = new Car('yellow')

Also, JS has built-in constructors like Object, Array, Function, so new Array() is equivalent to [], and new Object() is equivalent to {}:

let arr = new Array()
arr.push(1)
console.log(arr) // [1]

3.4 Prototype and prototype chain: where methods come from

When constructors create objects in bulk, having each instance copy its own methods wastes memory. JS solves this with prototypes:

The most important relationship between the two: an instance's __proto__ equals its constructor's prototype.

So the engine follows a chain when looking for properties:

First look for the object's own explicit property -> if not found, go to its __proto__ (prototype) -> if still not found, go up along the prototype... until the end.

This "look up" chain is the prototype chain (Prototype Chain).

Using Car from section 3.3: define a method on its prototype, and all instances share that method without needing to copy it:

// from section 3.3 function Car(color) { ... }
Car.prototype.info = function () {
    return 'I am a ' + this.color + ' Benz'
}
let car1 = new Car('red')
let car2 = new Car('blue')
car1.info() // car1 doesn't have its own info, finds it via prototype chain
car2.info() // all instances share the same method

3.5 Wrapper classes: why primitives can't have properties added

A common question: if a primitive value (like a string) is not an object, can we add a property to it? The answer: it won't throw an error, but the property won't be retained.

The reason lies in the wrapper class mechanism: when you write a string literal, the engine temporarily wraps it as an object with new String(...); but because the underlying value is still a primitive, the engine immediately performs "unboxing" afterward. So the property cannot persist:

var str = 'hello'
str.a = 2 // the engine temporarily wraps it into an object, adds a, then unboxes, so a doesn't stick
console.log(str.a) // undefined - primitives don't save properties
console.log(str) // hello

[!TIP] Conclusion: primitive types cannot hold properties long-term; only objects (reference types) can. To add properties, create an object.

Conclusion: the three are not isolated

Back to the opening question: why does getAge() output 18?

In summary, scope defines the rules of variable visibility, closure is a special case under those rules, and objects are the structures that carry these variables. The three examine different aspects of the same problem: where variables are visible, when they are retained, and how they are organized. Understanding them together is more complete than memorizing them as isolated definitions.