Question Bank
let, var, const, and Hoisting Conceptual Quiz
Difficulty: Easy
Walk through the scoping, redeclaration, and hoisting rules for `var`, `let`, and `const`, plus the TDZ trap that shows up in nearly every interview.
let, var, const, and Hoisting Conceptual Quiz
Walk through the scoping, redeclaration, and hoisting rules for `var`, `let`, and `const`, plus the TDZ trap that shows up in nearly every interview.
338 views
8
Walk through how var, let, and const differ in scope, redeclaration, and reassignment. Annotate the snippet below with which lines run and which throw.
Examples
Example 1:
Input: var x = 1; var x = 2; let y = 1; let y = 2; const z = 1; z = 2;
Output: var works, let y throws SyntaxError, z = 2 throws TypeError
Explanation: var is function-scoped and re-declarable, let is block-scoped and cannot be redeclared, const additionally rejects reassignment.Predict the output and explain why function declarations behave differently from var declarations under hoisting.
Examples
Example 1:
Input: console.log(squared(5)); function squared(num) { return num * num; }
Output: 25
Explanation: Function declarations are fully hoisted (binding and body), so they are callable above their textual definition.Trace each line and label every output with which scoping rule caused it. The point is to surface the TDZ behavior of let versus the undefined behavior of var.
Examples
Example 1:
Input: console.log(a); var a = 1; console.log(b); let b = 2;
Output: undefined, then ReferenceError on `console.log(b)`
Explanation: `var a` is hoisted and initialized to `undefined`. `let b` is hoisted but stays in the TDZ, so reading it before the `let b = 2` line throws.Use let plus a block to scope a per-iteration counter so the timeouts log 0, 1, 2. Then explain why swapping let for var would log 3, 3, 3.
Examples
Example 1:
Input: for (let i = 0; i < 3; i++) setTimeout(() => console.log(i), 0)
Output: 0 1 2
Explanation: `let` creates a fresh binding for each iteration, so each closure captures its own `i`. `var` would share a single function-scoped binding, which by the time the timeouts run holds `3`.