Question presented to candidate: "What does it mean for JavaScript to be lexically scoped, and how does the engine actually resolve a variable reference?"
What a strong answer should cover:
- Lexical scoping means a variable reference is resolved by WHERE the code is physically written in the source, not by how or from where the function is later called.
- The scope chain is the ordered list of nested scopes an engine walks outward through -- current scope, then its enclosing scope, then that scope's enclosing scope, and so on out to the global scope -- stopping at the first matching binding it finds.
- Lexical scope is fixed at the moment a function is DEFINED, not when it is called -- a function always resolves free variables against where it was written, no matter where it is later invoked from.
- Shadowing: an inner scope can declare a variable with the same name as an outer one; inside the inner scope, lookups resolve to the inner binding and the outer one is untouched.
- Scope visibility is one-directional -- an outer scope cannot see variables declared inside an inner scope's block or function.
- Closures are a direct consequence of lexical scoping: a function keeps the ability to resolve variables from its defining scope, which is exactly why that scope cannot be discarded even after the outer function returns.
Clarifying questions expected:
- "Would it help if I contrasted this with dynamic scoping, or should I focus on how it plays out in JavaScript specifically?"
Code / implementation expected: Yes -- a runnable snippet showing a 3-level nested scope chain resolving variables outward, plus a shadowing example.