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.

Creation phase, execution phase, and the TDZ. Switch between var, let, const and function forms under Tweak.
  1. Creation phase: The engine registers every declaration in the scope before running code.
  2. var: Initialised to undefined, so early reads return undefined.
  3. let / const: Registered but uninitialised: reading before the declaration throws a ReferenceError (the temporal dead zone).
  4. Function declarations: Hoisted with their body, so they can be called before their line.
  5. Function expressions: Follow their variable's rules: var greet is undefined, so calling it throws TypeError.

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

Common follow-up questions

Interview tips

Concepts covered

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

More JavaScript Interview questions