CodeZettaInterview Hub

JavaScript · Scope · Junior · Concept

How does the scope chain work when resolving a variable?

Short Interview Answer

The engine looks in the current lexical environment, then walks outer environments until it finds the binding or throws ReferenceError.

Detailed Explanation

Identifier resolution follows the lexical scope chain (static scope): nested functions close over the environment where they were defined, not where they are called. Lookup starts in the active Lexical Environment, then follows the `[[OuterEnv]]` link to parent environments, eventually reaching the global environment. If the binding is never found, you get a ReferenceError. Shadowing occurs when an inner binding hides an outer one with the same name. This chain is fixed at definition time for lexical bindings — which is the foundation of closures.

Example

const x = 'global';
function outer() {
  const x = 'outer';
  function inner() {
    console.log(x); // 'outer' — lexical, not caller
  }
  return inner;
}
const fn = outer();
fn();

Interview Tip

Emphasize lexical vs dynamic scope — JS is lexical (except rare `with`/`eval` cases).

Common Mistake

Claiming variables are resolved based on the call site (dynamic scope).

Did you know this answer?