JavaScript Hoisting and TDZ Code Traces
Six traces covering `var` declaration hoisting, function-declaration hoisting, TDZ access of `let`/`const`, and IIFE shadowing. Sharpens the mental model of when a binding exists vs. when it has a value.
Question Bank
Medium
JavaScript
6 questions
quiz
interview-prep
js-hoisting
js-language
642 views
9
What does the following code print?
Examples
Example 1:
Input: foobar()
Output: undefined
Explanation: The inner var foo declaration is hoisted to the top of the function but its assignment stays in place, so the log reads the local binding before it has a value.var foo = 1;
var foobar = function () {
console.log(foo);
var foo = 2;
};
foobar();What is the output of the following code?
Examples
Example 1:
Input: console.log(name); var name = 'John';
Output: undefined
Explanation: var name is hoisted and pre-initialized to undefined, so the reference resolves before the assignment runs.console.log(name);
var name = 'John';What does the following code print, and why does n print undefined instead of throwing?
Examples
Example 1:
Input: showNumber()
Output: undefined; undefined
Explanation: var n is hoisted and pre-initialized to undefined inside the function, and outer m is also still undefined when it is read.var m;
const showNumber = function () {
console.log(n);
console.log(m);
var n = 10;
m = 5;
};
showNumber();Trace what id holds after foo() returns. Why does the inner function id() declaration matter?
Examples
Example 1:
Input: foo(); console.log(id);
Output: 123
Explanation: The inner function id() declaration is fully hoisted and shadows the outer id, so id = 'abc' mutates the local binding only.var id = '123';
function foo() {
id = 'abc';
return;
function id() {}
}
foo();
console.log(id);What is the output of the following code? Walk through every binding the try/catch body introduces.
Examples
Example 1:
Input: trace the IIFE line by line
Output: 1; undefined; 2
Explanation: The catch parameter x shadows the var x inside the block, while y leaks to the function-scoped var that survives after the catch.(function () {
try {
throw new Error();
} catch (x) {
var x = 1, y = 2;
console.log(x);
}
console.log(x);
console.log(y);
})();What does this IIFE print, and why is the shadowing var not visible at the log call?
Examples
Example 1:
Input: trace the IIFE
Output: undefined
Explanation: Hoisting moves the inner var name declaration to the top of the IIFE so it shadows the outer 'John', but pre-initializes it to undefined.var name = 'John';
(function () {
console.log(name);
var name = 'Jane';
})();