Understanding JavaScript's Lexical Scope: A Fundamental Guide

Understanding JavaScript's Lexical Scope: A Fundamental Guide

By Michael Thornton

March 5, 2025 at 09:28 PM

JavaScript Lexical Scope diagram

JavaScript Lexical Scope diagram

Lexical scope, also known as static scope, determines how variable names are resolved in nested functions. In JavaScript, the scope of a variable is defined by its location within the source code, and this is determined during the lexing phase of compilation.

When a function is defined inside another function, the inner function has access to variables in its own scope, plus variables in the outer (enclosing) scope. This creates a scope chain that the JavaScript engine follows when looking up variables.

Consider this example:

function outer() {
    const message = 'Hello';
    
    function inner() {
        console.log(message); // Can access 'message'
    }
    
    inner();
}

The inner function can access variables from its parent scope because of lexical scoping. This is true even if the inner function is executed in a different scope.

Key points about lexical scope:

  • Variables defined in outer functions are accessible to inner functions
  • Inner functions cannot access variables from their calling scope
  • Variable lookup moves outward through the scope chain until it finds the first match
  • Each new function creates its own scope

Understanding lexical scope is crucial for writing maintainable JavaScript code and avoiding common scope-related bugs.

Related Articles

Previous Articles