Static vs Dynamic Scope
What you'll learn: You'll understand why JavaScript resolves variables at write-time (lexical/static scope) rather than call-time (dynamic scope).
The Two Models of Scope
When a function references a variable, the language must decide where to look for it. There are two philosophies:
Static (Lexical) Scope — The variable's location is determined by where the function is written in the code. The scope chain is locked in at author-time.
Dynamic Scope — The variable's location is determined by where the function is called from. The scope chain changes based on the call stack at runtime.
Why JavaScript Uses Static Scope
JavaScript (like most modern languages) uses static scope. When you define a function, it captures the scope environment from its physical location in the source code. This never changes, no matter where or how you call the function.
Think of it like a snapshot: the function takes a picture of its surrounding scope when it's created, and that picture travels with it forever.
const name = "Global";
function outer() {
const name = "Outer";
function inner() {
console.log(name); // Looks for 'name' where inner was WRITTEN
}
return inner;
}
const myFunc = outer();
myFunc(); // Logs "Outer" — not "Global"
Even though myFunc() is called in the global scope, inner still sees name from outer's scope because that's where it was defined.
If JavaScript used dynamic scope, inner would look for name based on where myFunc() was called — potentially seeing "Global" instead.
Why Static Wins
Static scope is predictable. You can trace variable resolution by reading the code once. Dynamic scope would make every function call potentially change behavior based on the call site — a debugging nightmare.
Key Takeaway: JavaScript uses lexical (static) scope, resolving variables based on where functions are written in the code, not where they're called — making code predictable and easier to reason about.