Scope Chain & Lexical Environment
Scope Chain & Lexical Environment in Modern JavaScript
Scope determines the visibility and accessibility of variables in JavaScript. Understanding how the JavaScript engine resolves variable references across nested functions requires mastering the Lexical Environment and the Scope Chain.
1. Lexical Scoping Explained
JavaScript uses Lexical Scoping (also called Static Scoping). This means:
Why? Because displayUser was lexically declared in the global scope. It resolves identifiers based on where it was born, not where it was invoked.
2. Structure of a Lexical Environment
Under the hood, every execution context has an associated Lexical Environment consisting of two components:
- 1Environment Record: The dictionary storing local variables, function declarations, and arguments.
- 2Reference to the Outer Lexical Environment: A pointer to the parent environment in which the function was physically created.
3. The Scope Chain Lookup Mechanism
When a variable is accessed inside a function:
- 1The engine checks the current function's local Environment Record.
- 2If not found, it follows the
outerreference to the parent Lexical Environment. - 3It repeats this traversal up the chain until finding the variable.
- 4If it reaches the Global Environment (
outer === null) and still cannot find the variable, it throws aReferenceError.
4. Block Scope vs Function Scope
varis Function Scoped: Ignores curly brace blocks (if,for,while). It leaks outside blocks!letandconstare Block Scoped: Create a new lexical block environment for every{ ... }pair.
Practice Quiz
Class Syntax & Constructor Methods
Continue learning with hands-on practice, examples, and exercises in the upcoming topic.
Related Lessons
| Previous Lesson | Next Lesson |
|---|---|
| Execution Context & Call Stack Deep Dive | Class Syntax & Constructor Methods |
Practice Quiz
Test your understanding of this lesson with 5 questions. Each question has one correct answer.