Hoisting & Temporal Dead Zone

Difficulty: Intermediate

Question

Explain hoisting in JavaScript. How do var, let, const, and function declarations behave differently?

Answer

Hoisting is JavaScript's default behavior of moving declarations to the top of their scope during the compilation phase. However, only declarations are hoisted, not initializations.

- var: hoisted and initialized with undefined - let/const: hoisted but NOT initialized (Temporal Dead Zone) - Function declarations: fully hoisted (both name and body) - Function expressions: only the variable is hoisted (not the function body)

Code examples

var Hoisting

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

// The engine sees it as:
// var x;          // declaration hoisted
// console.log(x); // undefined
// x = 5;          // assignment stays
// console.log(x); // 5

var declarations are hoisted and initialized with undefined. The assignment stays in place.

let/const and Temporal Dead Zone

// This throws ReferenceError
try {
  console.log(y);
  let y = 10;
} catch (e) {
  console.log(e.message);
}

// The TDZ exists from the start of the block
// until the declaration is encountered
{
  // TDZ starts here for 'z'
  // console.log(z); // would throw ReferenceError
  let z = 20; // TDZ ends here
  console.log(z); // 20
}

let and const are hoisted but remain in a 'Temporal Dead Zone' until the declaration line is reached.

Function Declaration vs Expression

// Function declaration - fully hoisted
console.log(greet('Alice'));
function greet(name) {
  return `Hello, ${name}!`;
}

// Function expression - only variable hoisted
try {
  console.log(farewell('Bob'));
} catch (e) {
  console.log(e.message);
}
var farewell = function(name) {
  return `Bye, ${name}!`;
};

Function declarations are fully hoisted. Function expressions with var hoist the variable as undefined, causing a TypeError when called.

Key points

Concepts covered

Hoisting, TDZ, var, let, const, Function Declaration