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

What is Lexical Scope?

Understanding how JavaScript determines variable accessibility based on where code is written, not where it runs.

What is Lexical Scope?

You'll learn how JavaScript decides which variables a function can access based on where you wrote the code, not where you run it.

The Core Idea

Lexical scope means that variable accessibility is determined by the physical structure of your code — by where functions are written in the source code. "Lexical" refers to the act of reading/writing code (like reading words in a book). When JavaScript executes a function, it looks for variables by checking the function's location in the code, then moving outward through parent scopes.

Think of it like Russian nesting dolls: an inner doll can see all the outer dolls that contain it, but only based on how they're physically nested — not based on which doll you pick up first.

How It Works

When you reference a variable, JavaScript:

  1. Checks the current function's scope
  2. If not found, checks the parent scope (where the function was defined)
  3. Continues outward until it finds the variable or reaches global scope
const outerVar = "I'm outside";

function outer() {
  const middleVar = "I'm in the middle";
  
  function inner() {
    console.log(outerVar);   // "I'm outside"
    console.log(middleVar);  // "I'm in the middle"
  }
  
  inner();
}

outer();

The inner function can access middleVar and outerVar because it's lexically inside outer, which is inside global scope. This access is determined at the moment you write the code, not when you call the function.

Key Takeaway: Lexical scope means functions can access variables from their parent scopes based on where they're written in the code, creating a nested, predictable chain of variable accessibility.