Skip to solution
mediumFrontend

What is lexical scoping and the scope chain?

936 views
01

Understand the problem

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.

scopelexical
02

Attempt it yourself

Sketch your approach before reading the solution — that's what interviews test.

Nudge consolestandby

Stuck? Beam a request up — the console returns a conceptual nudge that guides your logic without spoiling the implementation.

03

Study the solution

Target Audience: Engineers preparing for JavaScript fundamentals interview questions. Difficulty: Medium

How to read this doc: Concepts are explained in plain language first, then tagged with 📌 Interview term:. Every result below was actually run on Node.js v24.19.0 — the printed output is

Solution ready — 2 min read

Classified // press E to declassify

04

Run the code

JSA 3-level nested scope chain, resolved outward (run directly)
JSShadowing and one-way scope visibility (run directly)
05

Join the discussion

Discussion (0)

Sign in to join the discussion.

No responses yet. Be the first to share what you think.

Transmission complete // awaiting log

KEEP THE
STREAK ALIVE.

Dossier 58 of 165 decoded in the JavaScript track. One more won't hurt.

Back to track