
Understanding JavaScript's Lexical Scope: A Fundamental Guide

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

JavaScript Memory Management: A Guide to Efficient Performance Optimization
