Chapter 1JavaScript · Theory
Lexical Scope & Scope Chain
Scope is determined by where code is written, not where it runs.
JavaScript uses lexical (static) scoping: the scope of a variable is determined by its position in the source code. Functions create new scopes; blocks (if/for/while) create scopes with let/const.
When the engine looks up a variable, it starts in the current scope and walks outward through the scope chain until it finds a binding or reaches the global scope. This chain is established at write time, not run time.
Scope chain explains why inner functions can access outer variables but not vice versa, and why closures work across function calls — the chain is preserved in the closure's environment record.