CodeMasteryLab
Section 4

Hoisting & Temporal Dead Zone

Master JavaScript's hoisting behavior for variables and functions — one of the most commonly asked tricky concepts.

Hoisting & Temporal Dead Zone

Hoisting is a JavaScript mechanism where variable and function declarations are moved to the top of their scope during the compilation phase, before code executes.

Variable Hoisting

console.log(x); // undefined (not ReferenceError)
var x = 5;

console.log(y); // ReferenceError: Cannot access before initialization
let y = 10;

Function Hoisting

greet(); // Works! 'Hello'
function greet() { console.log('Hello'); }

shout(); // TypeError: shout is not a function
var shout = function() { console.log('HEY'); };

Temporal Dead Zone (TDZ)

let and const are hoisted but not initialized. The period between the start of the block and the declaration line is the TDZ. Accessing a variable in TDZ throws ReferenceError.

{
  // TDZ starts here for 'a'
  console.log(a); // ReferenceError
  let a = 1;      // TDZ ends here
}

Interview Prediction Output Questions

var a = 1;
function test() {
  console.log(a); // undefined (local var 'a' is hoisted)
  var a = 2;
  console.log(a); // 2
}
test();