Course contentsShow
← JavaScript
Lesson 82 of 2,7233. Variables and ScopeFree lesson

Lexical Scope

Inner scopes can access variables from outer scopes where they are defined.

Lexical Scope

What you'll learn: How JavaScript determines which variables a function can access based on where it's written in your code.

The Core Idea

Lexical scope (also called static scope) means that a function's access to variables is determined by its physical location in the code when you write it, not where you call it. Inner scopes can "see" variables from outer scopes where they are defined.

Think of it like nested boxes: an inner box can see and use what's in the outer box that contains it, but the outer box cannot reach into the inner box.

How It Works

When JavaScript looks for a variable, it starts in the current scope. If it doesn't find the variable there, it moves outward to the parent scope, then the grandparent scope, and so on—all the way up to global scope if needed.

let greeting = "Hello"; // global scope

function sayHi() {
  let name = "Alice"; // function scope
  
  if (true) {
    let punctuation = "!"; // block scope
    console.log(greeting + " " + name + punctuation); // "Hello Alice!"
    // Can access: punctuation (block), name (function), greeting (global)
  }
  
  // console.log(punctuation); // ERROR! Can't see inside the block
}

sayHi();

The if block can access punctuation, name, and greeting. The function can access name and greeting. But neither can reach inward to the block's variables.

Key Takeaway: Lexical scope means inner scopes can access variables from outer scopes based on where the code is written, creating a one-way visibility chain from inside-out.