var let const
Explain var vs let vs const in JavaScript. What is temporal dead zone?
Answers use simple, clear English.
Quick interview answer
var is function-scoped and hoisted (initialized undefined). let/const are block-scoped and hoisted but in TDZ until declaration — accessing early throws. const prevents rebinding the binding, not deep mutation of objects.
Detailed answer
var is function-scoped and hoisted (initialized undefined). let/const are block-scoped and hoisted but in TDZ until declaration — accessing early throws. const prevents rebinding the binding, not deep mutation of objects. Prefer const by default, let when reassignment needed; avoid var in modern code. TDZ exists so block bindings behave predictably before initialization.
Full explanation
TDZ exists so block bindings behave predictably before initialization.
Real example & use case
Loop counters use let; module-level config object uses const but may mutate properties carefully.
Pros & cons
Pros of let/const: fewer hoist bugs. Cons: const misconception that objects are immutable.
Code example
function demo() {
// console.log(x); // TDZ ReferenceError
let x = 1;
const cfg = { ok: true };
cfg.ok = false; // allowed
// cfg = {}; // TypeError
}Practice code · javascript (view only · no execution)
function demo() {
// console.log(x); // TDZ ReferenceError
let x = 1;
const cfg = { ok: true };
cfg.ok = false; // allowed
// cfg = {}; // TypeError
}