Curriculum
Module 13 // Core JavaScript
Scope Chain & Lexical Environment
Module Objective
Variable resolution, nested scopes, shadowing
Mental Model Realtime Simulation
INTERACTIVE_CANVASEditor_Pane
Loading...
Console_Output
Waiting for output...
Practical Code Examples
// Example 1
// 1. Variable Shadowing
const name = "Global";
function demo() {
const name = "Local"; // Shadows global name
console.log(name); // "Local"
}
demo();
console.log(name); // "Global"💡 Shadowing happens when a variable in a local scope has the same name as one in an outer scope. The engine stops at the first match it finds in the chain.
// Example 2
// 2. Lexical Scope (Static Scope)
const x = 10;
function printX() {
console.log(x);
}
function outer() {
const x = 20;
printX(); // What will this print?
}
outer(); // Output: 10💡 JavaScript uses **Lexical Scope**. A function's scope is determined by where it is **written** in the code, not where it is **called**. `printX` was written in the global scope, so it looks there for `x`.
// Example 3
// 3. Block Scope Chain
{
const a = 1;
{
const b = 2;
console.log(a); // ✅ 1
}
// console.log(b); // ❌ ReferenceError
}💡 Each block `{}` creates its own environment. The inner block can access the outer block's variables, but not vice-versa.
Engine & Memory Architecture
The Chain in Memory
1. Lexical Environment:
- Every execution context has a reference to its Outer Environment.
- This linked list of environments is the physical Scope Chain.
2. Variable Resolution:
- When you use a variable, the CPU doesn't just look at one spot in RAM.
- It "walks" the linked list of environments in the Stack/Heap.
- Each step outward is a memory lookup. Deeply nested chains can be slightly slower.
3. Global Object:
- The end of the chain is always the Global Object (
windowin browsers,globalin Node). - If the lookup fails here, the engine throws a
ReferenceError.