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.
varat the top level creates a property onwindow;letandconstdon't.varallows redeclaring in the same scope;letandconstdon't.- Default to
const, useletwhen you reassign, and avoidvar.
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 constantCommon follow-ups
- How do you make an object truly immutable?
Object.freeze(shallow), oras constin TypeScript at the type level. - Why does
letfix thesetTimeoutloop 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
letandconstaren't hoisted at all.