Search lands in PR-5.1 (Pagefind).

Explanation Beginner

Chapter 7 Updated

let, const, Temporal Dead Zone, Block Scope & Shadowing

The modern declarations, their scoping rules, and the three errors they produce.

  • Full 15m
  • Revision 3m
  • Flow 2m

let / const lifecycle — from TDZ to safe zone

flowchart TD
    S["<b>i · Scope entry</b><br/>Phase 1 allocates memory<br/>for every let / const"]
      --> T["<b>ii · Temporal Dead Zone</b><br/>variable exists, but unreachable"]
    T -->|"<b>iii</b> · access before declaration"| RE["<b>ReferenceError</b><br/>Cannot access 'x' before initialization"]
    T -->|"<b>iv</b> · declaration line runs"| L["<b>v · Safe zone</b><br/>bound to its initial value"]
    L -->|"<b>vi</b> · let reassignment"| L
    L -->|"<b>vii</b> · const reassignment"| TE["<b>TypeError</b><br/>Assignment to constant variable"]
    L -->|"<b>viii</b> · duplicate declaration"| SE["<b>SyntaxError</b><br/>Identifier 'x' has already been declared"]
    L -->|"<b>ix</b> · scope exits"| D["<b>GC</b><br/>block memory destroyed"]
 
    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,D node
    class T warn
    class L ok
    class RE,TE,SE err
  • Scope entry

    When execution enters the scope, Phase 1 allocates memory for every `let` / `const` in that scope — before any code runs.

  • Temporal Dead Zone

    Variable exists in memory but is flagged as unreachable. Lives in Script scope (top-level) or Block scope (inside `{ }`).

  • TDZ violation

    Reading, writing, or even `typeof` in the TDZ throws `ReferenceError: Cannot access 'x' before initialization`.

  • Declaration runs

    The `let x = …` / `const x = …` line executes. The TDZ ends, the variable is bound to its initial value.

  • Safe zone

    Normal access works. Reads return the value, `typeof` returns the type.

  • let reassignment

    `let` allows rebinding to a new value. The variable stays in the safe zone.

  • const reassignment

    `const` forbids rebinding → `TypeError: Assignment to constant variable`. Mutating object properties is still allowed.

  • Duplicate declaration

    A second `let` / `const` / `var` with the same name in the same scope throws `SyntaxError` — the code never runs.

  • Scope exit

    When the block or function returns, block-scoped `let` / `const` memory is destroyed. Script-scope bindings live for the page.

Comments

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