Skip to the solution
EasyPhone Screen8 min read

Describe the concept of 'scope' in JavaScript.

795 views

The problem

Question presented to candidate: "Explain what scope means in JavaScript, and walk me through the practical difference between how var, let, and const each decide where a variable lives."

What a strong answer should cover:

  • Scope is the region of code where a given variable name can be looked up; a name lookup walks outward through enclosing scopes (the scope chain) but never inward.
  • var is function-scoped (or global-scoped at the top level) β€” it ignores block boundaries like if and for, so a var declared inside a block is still visible after that block ends.
  • let and const are block-scoped β€” confined to the nearest enclosing curly-brace block.
  • let and const are hoisted but sit in the temporal dead zone until their declaration line executes, so reading them earlier throws a ReferenceError; var is accessible (as undefined) before its own declaration line runs.
  • The classic var-in-a-loop-closure bug: closures built inside a var-based for loop all share one variable and see its final value; a let-based loop gives each closure its own per-iteration binding.

Clarifying questions expected:

  • "Should I also cover the temporal dead zone, or just the block-versus-function distinction?"
  • "Is this specifically about lexical scope, or should I also touch on this-binding, which is a separate mechanism?"

Code / implementation expected: Yes β€” a short, runnable snippet demonstrating var leaking out of a block, the TDZ throwing on early access, and the classic var-vs-let loop-closure difference.

  • scope
  • variables
  • functions
  • global

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.

JavaScriptScope in practice: var leaking past a block, the TDZ, and the var-vs-let loop-closure bug (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 14 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 nextEasy

What does Object.hasOwn() do differently from Object.prototype.hasOwnProperty.call(), and why is it the recommended modern replacement?

Continue