Lexical Binding Explained
You'll learn: How lexical (static) binding resolves variable references based on where code is written, not where it runs.
What is Lexical Binding?
Lexical binding means that variable references are resolved by looking at the physical structure of your code — specifically, where functions and variables are defined in the source text. The word "lexical" comes from "lexing," the phase when JavaScript reads your code.
This is static because the bindings are determined at parse time, before any code executes. JavaScript looks at the nesting structure of your functions to figure out which variables each function can access.
How It Works
When you reference a variable inside a function, JavaScript resolves it by:
- Checking the current scope
- If not found, checking the outer scope where the function was written
- Continuing up the scope chain until it finds the variable or reaches global scope
The key: It uses where the function was defined, not where it's called from.
const outer = 'I am outer';
function showOuter() {
console.log(outer); // Lexically bound to the outer variable above
}
function different() {
const outer = 'Different outer';
showOuter(); // Still logs "I am outer", not "Different outer"
}
different();
Why "Lexical" Matters
Think of lexical binding like a family tree drawn on paper. No matter where you take that paper, the relationships stay the same. Similarly, no matter where you call a function, its variable references are already "wired" to the scopes where it was written.
Key Takeaway: Lexical binding resolves variables by code structure at parse time, creating permanent connections between functions and their surrounding scopes — regardless of where those functions are eventually called.