Skip to main content
03

var vs let vs const: hoisting and the temporal dead zone

EasyJavaScriptHoistingTDZ

What's the difference between var, let and const? Explain hoisting and the temporal dead zone.

TL;DR

var is function-scoped, hoisted and initialized to undefined, so you can read it before its line without an error. let and const are block-scoped. They're hoisted too, but stay uninitialized until their declaration runs. Touching them before that throws a ReferenceError; that window is the temporal dead zone (TDZ). const also can't be reassigned, but the object it points to can still change.

Key points

  • Hoisting: declarations are registered when the scope is created, before any code runs.
  • Function declarations are hoisted fully, so you can call them before they appear. Function expressions and arrow functions follow their variable's rules.
  • var at the top level creates a property on window; let and const don't.
  • var allows redeclaring in the same scope; let and const don't.
  • Default to const, use let when you reassign, and avoid var.

Example

js
console.log(a) // undefined (var is hoisted and initialized)
var a = 1

console.log(b) // ReferenceError: b is in the TDZ
let b = 2

const user = { name: 'Dana' }
user.name = 'Noa' // fine: the object is mutable
user = {} // TypeError: the binding is constant

Common follow-ups

  • How do you make an object truly immutable? Object.freeze (shallow), or as const in TypeScript at the type level.
  • Why does let fix the setTimeout loop bug? It creates a new binding for each loop iteration.

What interviewers look for

Tip

Function scope vs block scope, "hoisted but uninitialized" for let/const, and const meaning a constant binding, not an immutable value.

  • Red flag: saying let and const aren't hoisted at all.

Was this helpful?

Related questions