Back to series
· 8 min read

Scope and Lexical Scope


1. What Is Scope

Scope refers to the effective range within which identifiers in a program (variables, functions, classes, etc.) can be accessed and referenced.

Simply put, scope answers a core question:

At a given point in a program, which variables and functions can be accessed?

For example:

const name = "Reverie";

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

greet();

console.log(name);
// console.log(message); // ReferenceError

There are two different scopes here:

  • Global scope: defines name, which is accessible inside the function.
  • Function scope: defines message, which can only be accessed inside the greet function.

Whether a variable can be accessed depends on where it is declared and on the scope lookup rules defined by the language.

1.1 The Core Role of Scope

Scope not only determines whether a variable can be accessed; it also fulfills the following responsibilities:

  1. Name isolation: allows different areas of code to use the same variable name.
  2. Access control: restricts the visible range of variables and functions.
  3. Module encapsulation: hides internal implementation details and exposes only the necessary interface.
  4. Dependency management: makes clear which external variables a function depends on.
  5. Support for lifetime management: affects when a variable binding is no longer reachable, but is not directly equivalent to an object's lifetime.

1.2 Scope and Variable Declaration Position

const value = 100;

function outer() {
    const value = 200;

    function inner() {
        const value = 300;
        console.log(value);
    }

    inner();
}

outer();

Output:

300

Although all three variables are named value, they belong to different scopes.

A variable in an inner scope shadows a variable with the same name in an outer scope.

2. Main Types of Scope

Different programming languages classify scope differently. Common categories include global scope, function scope, block scope, and module scope.

2.1 Global Scope

Global scope is the relatively top-level scope in a program.

Variables declared in this scope can be accessed from other scopes in accordance with the language's rules.

JavaScript example:

const appName = "Reverie";

function showAppName() {
    console.log(appName);
}

showAppName();

appName is declared in the global scope, so showAppName can access it.

Different languages define global scope in ways that are not entirely the same:

  • JavaScript: browser scripts and modules have different top-level binding rules.
  • Python: top-level names in a module belong to the module namespace.
  • C: file-scope variables have internal or external linkage.
  • Go: package-level declarations belong to the package block.
  • Java: there is no free-variable-style global scope exactly like JavaScript's; top-level declarations usually belong to a class or interface.

Note: global visibility does not mean a variable can be accessed directly from any file, module, or process.

2.2 Function Scope

Function scope means that a variable's accessible range is determined by function boundaries.

JavaScript example:

function calculate() {
    var result = 100;

    if (true) {
        var message = "Success";
    }

    console.log(result);
    console.log(message);
}

calculate();

// console.log(result); // ReferenceError

Variables declared with var have function scope, not block scope.

Therefore, even though message is declared inside the if block, it can be accessed throughout the function.

Function scope is common in:

  • JavaScript's var.
  • Function-local names in Python.
  • Block-scope declarations inside functions in C and C++ (strictly speaking, C/C++ mainly use the concept of block scope).
  • Local variables declared inside Java methods.

2.3 Block Scope

Block scope is scope delimited by block boundaries.

Common blocks include:

{
    // code block
}

JavaScript example:

function test() {
    if (true) {
        let value = 100;
        const name = "Reverie";
        var status = "OK";
    }

    console.log(status);

    // console.log(value); // ReferenceError
    // console.log(name);  // ReferenceError
}

Here:

  • let: block scope.
  • const: block scope.
  • var: function scope or the corresponding binding in the global script environment.

Block scope prevents temporary variables from leaking into the outer environment.

2.4 Module Scope

Module scope is used to isolate variables and functions declared inside a module.

JavaScript ES Modules example:

// user.js
const internalToken = "secret";

export function getUser() {
    return {
        name: "Alice"
    };
}

Other modules can import getUser, but they cannot directly access the non-exported internalToken.

// app.js
import { getUser } from "./user.js";

console.log(getUser());

// internalToken is not an accessible binding of the current module

The main value of module scope:

  • Prevent global naming conflicts.
  • Isolate module-internal implementation.
  • Make module dependencies explicit.
  • Support code organization and encapsulation.

2.5 Comparison of Scope Types

Scope Type Main Boundary Typical Scenario
Global scope Top level of the program or runtime environment Global declarations
Function scope Function boundary Variables inside functions
Block scope Code block boundary such as {} Variables inside conditions and loops
Module scope Module boundary Module-internal declarations

Note: Not all languages use exactly the same model for these classifications. For example, C and C++ use terms such as file scope and block scope; Java uses different naming and visibility rules based on classes, methods, blocks, and packages.

III. What Is Lexical Scope?

Lexical scope, also called static scope, means that the accessibility relationships of variables are determined by where the code is defined in the source file, not by where the function is actually called.

This is key to understanding closures and functional programming.

3.1 Core Rules of Lexical Scope

In the lexical scope model:

  • A function can access variables in its own scope.
  • A function can access variables in the outer scope where it is defined.
  • A function cannot automatically access the caller's local variables just because it is called by some function.
  • A variable with the same name resolves first to the declaration in the current scope.

For example:

const name = "Global";

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

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

    inner();
}

outer();

Output:

Outer

inner is defined inside outer, so it can access outer's lexical environment.

3.2 How to Determine Lexical Scope

To determine which external variables a function can access, look first at where the function is defined, not where it is called.

const value = "Global";

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

    return function inner() {
        console.log(value);
    };
}

const fn = outer();

function execute() {
    const value = "Execute";
    fn();
}

execute();

Output:

Outer

Although fn is called inside execute, it still accesses value from the lexical environment where it was defined.

It does not automatically switch to accessing variables in execute just because the call site changes.

3.3 Structure of Lexical Scope

flowchart TD
    A["Global scope"] --> B["outer function scope"]
    B --> C["inner function scope"]
    C --> D["Search current scope"]
    D --> E{"Is the variable found?"}
    E -->|"Yes"| F["Return variable binding"]
    E -->|"No"| G["Search outer lexical scopes"]
    G --> H{"Has the global scope been reached?"}
    H -->|"No"| G
    H -->|"Yes"| I["Lookup failed"]

    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:#E8EDF2,stroke:#B8C3CE,color:#334155
    style F fill:#E5F4EC,stroke:#A3CBB5,color:#334155
    style G fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
    style H fill:#E8EDF2,stroke:#B8C3CE,color:#334155
    style I fill:#F3EDFC,stroke:#C4B2E3,color:#334155

    linkStyle default stroke:#A3B8AC,stroke-width:1.5px

4. Lexical Scope and Dynamic Scope

Understanding lexical scope requires comparing it with dynamic scope.

The core difference between the two is:

  • Lexical scope: the variable lookup relationship is determined by where the function is defined.
  • Dynamic scope: the variable lookup relationship is determined by the function call chain.

4.1 Lexical Scope Example

const name = "Global";

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

function execute() {
    const name = "Local";
    printName();
}

execute();

Output:

Global

Because printName is defined in the global scope, it accesses the outer binding corresponding to its definition location.

4.2 The Assumption of Dynamic Scope

If the dynamic scope model were used, variable lookup would proceed along the actual call chain.

In the above logic:

execute
    → printName

printName might find name in the caller execute, and thus output:

Local

But JavaScript uses lexical scope, so the actual output is Global.

4.3 Comparison of the Two

Comparison dimension Lexical scope Dynamic scope
Basis of lookup Function definition location Function call chain
Variable relationship Mostly determined when writing the code Determined at runtime according to the call chain
Predictability Relatively high Depends on the runtime call path
Closure support Forms naturally Requires a different environment management mechanism
Common languages JavaScript, Python, Java, C, Go, Rust A few languages or specific dynamic binding mechanisms

Most modern mainstream general-purpose programming languages use lexical scope.

Note that dynamic scope is not the same as dynamic typing, nor is it the same as dynamic binding. These are three concepts at different levels.

5. Scope Chain

The scope chain is the logical relationship used during variable lookup, where a variable is searched for level by level from the current scope outward through outer scopes.

When a program accesses a variable, the runtime searches for the corresponding binding in the current scope and its outer environments according to the language rules.

5.1 Scope Chain Example

const a = 10;

function outer() {
    const b = 20;

    function middle() {
        const c = 30;

        function inner() {
            const d = 40;

            console.log(a, b, c, d);
        }

        inner();
    }

    middle();
}

outer();

inner can access:

  • d: current function scope.
  • c: outer middle scope.
  • b: outer outer scope.
  • a: global scope.

5.2 Variable Lookup Process

flowchart TD
    A["Access variable x"] --> B["Search current scope"]
    B --> C{"Found x"}
    C -->|"Yes"| D["Return corresponding binding"]
    C -->|"No"| E["Search outer scope"]
    E --> F{"Found x"}
    F -->|"Yes"| D
    F -->|"No"| G["Continue searching outward"]
    G --> H{"Reached outermost scope"}
    H -->|"No"| E
    H -->|"Yes"| I["Throw undefined variable error or handle according to language rules"]

    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:#E5F4EC,stroke:#A3CBB5,color:#334155
    style E fill:#FFF5DE,stroke:#E8D29A,color:#334155
    style F fill:#F3EDFC,stroke:#C4B2E3,color:#334155
    style G fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
    style H fill:#E8EDF2,stroke:#B8C3CE,color:#334155
    style I fill:#E8EDF2,stroke:#B8C3CE,color:#334155

    linkStyle default stroke:#A3B8AC,stroke-width:1.5px

5.3 Variable Shadowing

When an inner scope declares a variable with the same name as one in an outer scope, the inner variable shadows the outer variable.

const value = 100;

function outer() {
    const value = 200;

    function inner() {
        const value = 300;
        console.log(value);
    }

    inner();
}

outer();

Output:

300

When looking up a variable, the runtime prioritizes the matching binding in the current scope.

If value has already been found in the current scope, it will not continue searching for a variable with the same name in outer scopes.

Variable shadowing should be used with caution in large programs; otherwise it may reduce code readability and even cause unexpected behavior.

6. Lexical Environment

Lexical scope describes the static accessibility relationships of variables, while the lexical environment (Lexical Environment) is an important concept used by language runtimes to implement these relationships.

Taking ECMAScript as an example, a lexical environment is an abstract mechanism in the specification used to manage identifier bindings and references to outer environments.

6.1 Composition of a Lexical Environment

Conceptually, a lexical environment mainly contains:

  1. Environment Record: stores identifier bindings in the current environment.
  2. Outer Environment Reference: points to the outer lexical environment.

It can be abstractly represented as:

LexicalEnvironment = (EnvironmentRecord,\ OuterReference)

Where:

  • EnvironmentRecord: stores bindings corresponding to variables, functions, and other declarations.
  • OuterReference: establishes the lookup relationship between the current environment and outer environments.

This is an abstract description at the specification level; it does not mean that engines necessarily use the same names or structures in their implementations.

6.2 Nesting Relationships of Lexical Environments

For example:

const globalValue = 10;

function outer() {
    const outerValue = 20;

    function inner() {
        const innerValue = 30;
        return globalValue + outerValue + innerValue;
    }

    return inner();
}

It can be abstracted as:

Global lexical environment
    └── outer lexical environment
            └── inner lexical environment

Each environment establishes a relationship through an outer reference.

When accessing a variable, the lookup starts from the current environment and proceeds along outer references.

6.3 Lexical Environments and Execution Contexts

The two are related, but they should not be conflated.

Concept Core Meaning
Lexical Environment Manages identifier bindings and relationships to outer environments
Execution Context Describes the running state during code execution
Scope Specifies the range in which names are accessible
Scope Chain Describes the logical path for variable lookup toward outer layers

In ECMAScript, an execution context is associated with specification structures such as the lexical environment and the variable environment.

Different languages and runtimes do not necessarily adopt exactly the same model.

7. Lexical Scope and Closures

A closure is an important manifestation of lexical scope in scenarios such as function return, deferred execution, and environment retention.

A closure is formed when a function references variables in the outer scope at its definition site and can still access these variables afterward.

7.1 Basic Example

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

Here:

  • createCounter creates the local variable count.
  • The inner function references count.
  • The inner function is returned.
  • After the outer function finishes executing, the returned function can still access count.

This shows that a function's access capability depends not only on the current call stack but also on the lexical environment associated with it.