var, let, and const
console.log(x); // undefined
var x = 1;
console.log(y); // ReferenceError: Cannot access 'y' before initialization
let y = 2;
const list = [];
list.push(1); // fine — the array is mutated, not reassigned
Both reads happen before the declaration, yet one quietly prints undefined and the other throws. All three keywords declare variables, but they differ in scope, reassignment, and when they become usable.
varis function-scoped (or global). It is hoisted to the top of its function and initialised toundefined, so reading it before its line givesundefinedrather than an error.letandconstare block-scoped: they exist only inside the nearest{ ... }. They are hoisted too, but not initialised — the gap between the start of the block and the declaration is the temporal dead zone, and touching the variable there throws aReferenceError.constmust be given a value at declaration and cannot be reassigned. It is not immutable: the binding is fixed, but the object it points at can still be mutated.
Prefer const, fall back to let when you must reassign, and avoid var. A
let binding inside a loop is also fresh on every iteration, which is why
closures capture the right value where var would share one.
You are about to answer a short quiz on var, let, and const.