Skip to the solution
MediumFrontend8 min read

What is lexical scoping and the scope chain?

936 views

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.

  • scope
  • lexical

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

8 min read Β· 9 sections

Run the code

Edit the code and run it here. Each console line with an expected value becomes a test.

JavaScriptA 3-level nested scope chain, resolved outward (run directly)
JavaScriptShadowing and one-way scope visibility (run directly)

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 58 of 165 in JavaScript

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

Up nextMedium

How do you implement a deepFreeze function recursively?

Continue