mediumpredictionjavascript~8 min
Hoisting and the Temporal Dead Zone
Objective: Distinguish hoisting of declarations from initialization, and recognize the temporal dead zone.
Predict what each line prints. Pay attention to how `var`, function declarations, `let` and `const` behave before and after their declaration.
- Write one line per console.log, in order.
- Write values only, without quotes (e.g. `undefined`, `function`, `ReferenceError`).
Read the code, then type what it prints
console.log(typeof hoistedVar);
console.log(typeof hoistedFn);
console.log(typeof fnExpression);
var hoistedVar = 1;
function hoistedFn() {}
var fnExpression = function () {};
try {
console.log(tdz);
} catch (e) {
console.log(e.name);
}
let tdz = 2;
try {
const k = 1;
k = 2;
} catch (e) {
console.log(e.name);
}Output
> Nothing has run yet.
Interview follow-up questions
- Is `let` hoisted? What evidence would you give?
- Why does `typeof` on an undeclared variable not throw, but on a TDZ variable does?
- How do ES modules change hoisting of imports?