JavaScript Variable Hoisting: var vs let/const Explanations Quiz
Two seeded explanations (var hoisting and the let/const TDZ) plus two companion drills covering function-declaration hoisting and a common interview trap.
Question Bank
Medium
JavaScript
4 questions
quiz
js-hoisting
variables
fundamentals
770 views
9
Explain what variable hoisting means for var declarations and predict the output of the snippet below.
Examples
Example 1:
Input: console.log(num); var num = 10;
Output: undefined
Explanation: The declaration is hoisted to the top of the function or global scope and pre-initialized with undefined; only the assignment stays in place.Example 2:
Input: foo(); function foo() { console.log('hi'); }
Output: 'hi'
Explanation: Function declarations are hoisted with their body, not just their name, so the call before the declaration still works.console.log(num);
var num = 10;Now describe how let and const differ from var under hoisting, and explain what the Temporal Dead Zone (TDZ) is.
Examples
Example 1:
Input: console.log(num); let num = 10;
Output: ReferenceError: Cannot access 'num' before initialization
Explanation: The binding exists (it was hoisted) but is in the TDZ until the let line, so any access throws.Example 2:
Input: { let x = 1; { console.log(x); let x = 2; } }
Output: ReferenceError: Cannot access 'x' before initialization
Explanation: The inner block has its own hoisted (but un-initialized) `x`, which shadows the outer one and is in the TDZ at the console.log line.console.log(num); // what happens?
let num = 10;
console.log(value); // and here?
const value = 5;Function declarations and function expressions both look like 'functions' but hoist very differently. Predict the output of the snippet below and explain why.
Examples
Example 1:
Input: hi(); bye(); function hi(){console.log('hi')} var bye = function(){console.log('bye')};
Output: 'hi' then TypeError: bye is not a function
Explanation: `hi` is a function declaration so its body is hoisted; `bye` is a var holding a function expression, so the var is hoisted as undefined and the call throws.hi();
bye();
function hi() {
console.log('hi');
}
var bye = function () {
console.log('bye');
};Interview trap: walk through what each console.log prints in the loop below, then rewrite it with let to fix the bug.
Examples
Example 1:
Input: for (var i = 0; i < 3; i++) setTimeout(() => console.log(i), 0);
Output: 3, 3, 3
Explanation: All three closures share the single var-scoped `i`, which is 3 by the time the timers fire.Example 2:
Input: for (let i = 0; i < 3; i++) setTimeout(() => console.log(i), 0);
Output: 0, 1, 2
Explanation: `let` creates a fresh per-iteration binding, so each closure captures its own `i`.for (var i = 0; i < 3; i++) {
setTimeout(() => console.log(i), 0);
}