Explain the difference in hoisting between `var`, `let`, and `const`

HighIntermediateJavascript
Preparing for interviews?

Use guided tracks for structured prep, then practice company-specific question sets when you want targeted interview coverage.

Quick Answer

All variable declarations are hoisted, but only var is initialized with undefined. Variables declared with let and const exist in the temporal dead zone until execution reaches their declaration, making them inaccessible beforehand.

Answer

The Core Idea

All variable declarations are hoisted — meaning they’re recognized by JavaScript before execution. However, only var is initialized immediately with undefined. let and const are hoisted too, but they stay in the temporal dead zone (TDZ) until the actual declaration line.

Keyword

Hoisted?

Initialized Before Declaration?

Accessible Before Declaration?

Reassignable?

Redeclarable?

var

✅ Yes

✅ Initialized to undefined

✅ Yes (but value = undefined)

✅ Yes

✅ Yes

let

✅ Yes

❌ Not initialized (TDZ)

❌ No — ReferenceError

✅ Yes

❌ No

const

✅ Yes

❌ Not initialized (TDZ)

❌ No — ReferenceError

❌ No (must initialize immediately)

❌ No

Hoisting and accessibility differences between var, let, and const.

How It Works Under the Hood

When the JavaScript engine creates an execution context, it allocates memory for all declared variables:

  • var is assigned undefined immediately.
  • let and const are known but remain uninitialized until their declaration line is reached.
JAVASCRIPT
// Example 1: var
console.log(a); // undefined
var a = 10;

// Example 2: let
console.log(b); // ❌ ReferenceError (TDZ)
let b = 10;

// Example 3: const
console.log(c); // ❌ ReferenceError (TDZ)
const c = 10;
                  

The Temporal Dead Zone (TDZ)

The TDZ is the time between entering a scope and the moment a let or const variable is declared. Accessing it during this period throws a ReferenceError. It helps prevent using variables before they're safely initialized.

JAVASCRIPT
{
  // TDZ starts
  console.log(x); // ❌ ReferenceError
  let x = 5; // TDZ ends here
  console.log(x); // ✅ 5
}
                  
Still so complicated?

Imagine you’re checking into a hotel 🏨. Rooms (var, let, const) are reserved at check-in (hoisting), but only var gets its key immediately. let and const exist but you can’t enter until the receptionist actually hands over the key — that’s the temporal dead zone!

Summary
  • All declarations are hoisted, but initialization differs.
  • var → hoisted + initialized as undefined.
  • let / const → hoisted but uninitialized (TDZ).
  • Accessing let or const before declaration → ReferenceError.
  • const also requires immediate initialization.
Similar questions
Guides
7 / 61