Course contentsShow
← JavaScript
Lesson 492 of 2,72313. ClosuresFree lesson

Lexical Scope is Determined at Parse Time

Understanding that scope relationships are fixed when code is parsed, before any execution occurs.

Lexical Scope is Determined at Parse Time

You'll learn: Why scope relationships in JavaScript are locked in when your code is parsed, not when it runs.

The Key Insight

When JavaScript encounters your code, it first parses it (reads and analyzes the structure) before executing anything. During this parsing phase, the engine determines all scope relationships based on where functions are written in the source code. This means scope is decided by the physical placement of your code, and it never changes—even if functions are called from different places at runtime.

Parse Time vs Runtime

Think of it like a blueprint for a building. When the architect draws the plans (parse time), they decide which rooms connect to which hallways. Once construction starts (runtime), people can move through the building in different ways, but the physical layout doesn't change based on how they walk around.

let outer = "I'm outside";

function first() {
  let inner = "I'm inside first";
  
  function second() {
    console.log(outer); // Can access outer
    console.log(inner); // Can access inner
  }
  
  return second;
}

const myFunc = first();
myFunc(); // Still accesses both variables

When JavaScript parses this code, second is written inside first, which is written in the global scope. Those scope relationships are permanent. Even though myFunc() is called in the global scope, second still has access to inner because the scope chain was determined when the code was parsed, not when myFunc() runs.

Key Takeaway: Lexical scope is fixed at parse time based on where functions are written in your source code—runtime execution cannot change these scope relationships.