Search lands in PR-5.1 (Pagefind).

Explanation Beginner

Chapter 6 Updated

Scope Chain, Scope & Lexical Environment

How JS finds variables — the lookup mechanism that powers closures and modules.

  • Full 14m
  • Revision 3m
  • Flow 2m

The Scope Chain — variable lookup walks outward

flowchart TD
    S["<b>i · Need variable <code>x</code></b><br/>lookup starts in current EC"]
      --> C{"<b>ii</b> · In <b>local memory</b>?"}
    C -->|"Yes"| H["<b>vi</b> · Return value (or <code>undefined</code>)"]
    C -->|"No"| P1{"<b>iii</b> · Outer parent's memory?"}
    P1 -->|"Yes"| H
    P1 -->|"No"| P2{"<b>iv</b> · Grandparent's memory? ...up the chain"}
    P2 -->|"Yes"| H
    P2 -->|"No"| G{"<b>v</b> · Found in Global scope?"}
    G -->|"Yes"| H
    G -->|"No — outer ref is null"| E["<b>vii</b> · ReferenceError<br/>x is not defined"]
 
    classDef ok   fill:#e7efd9,stroke:#587640,stroke-width:2px,color:#1a1915;
    classDef warn fill:#fdecd3,stroke:#c2410c,stroke-width:2px,color:#1a1915;
    classDef err  fill:#f5d4cf,stroke:#991b1b,stroke-width:2px,color:#1a1915;
    classDef node fill:#f5efe1,stroke:#6a8a4f,stroke-width:2px,color:#1a1915;
    class S,C,P1,P2,G node
    class H ok
    class E err
  • Lookup starts

    Any identifier reference triggers a lookup inside the currently executing function's lexical environment.

  • Local memory

    First check the function's own variables and parameters. Found here → stop, return the value.

  • Parent's environment

    Follow the outer environment reference to the function where this one was *lexically written* — not where it was called.

  • Climb the chain

    Repeat outward through each ancestor lexical environment. Inner → outer → grandparent → ... — one hop per level.

  • Global scope

    The end of every chain. Global's outer reference is `null`. If it's not here, it isn't anywhere.

  • Hit

    Variable found. Stops immediately at the first match — outer occurrences are shadowed.

  • Miss

    Chain exhausted with no match. `ReferenceError: x is not defined` is thrown.

Comments

Comments are disabled in this environment. Set PUBLIC_GISCUS_REPO, PUBLIC_GISCUS_REPO_ID, and PUBLIC_GISCUS_CATEGORY_ID to enable.