CodePark/ questions / Scope & hoisting
START PRACTICINGPRACTICE
Frontend question · JavaScript › Scope & hoisting

What happens when this runs?

console.log(a);
var a = 1;
console.log(b);
let b = 2;
Logs undefined, then throws a ReferenceError

var a is hoisted and set to undefined, so the first log prints undefined. let b is also hoisted, but it stays in the temporal dead zone (TDZ) until its declaration line runs. Reading it there throws ReferenceError: Cannot access 'b' before initialization.

The tempting option "Logs
undefined twice" is wrong because let is not set to undefined when hoisted. Only var is.