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.