What is the difference between var, let, and const?
In JavaScript, variables can be declared using var, let, or const. The differences lie in scoping, hoisting, and re-assignment:
- βΊScope:
varis function-scoped. If defined inside a function, it is only available inside that function.letandconstare block-scoped, meaning they are only accessible within the nearest curly braces{}(e.g., if-statements, loops). - βΊHoisting:
varvariables are hoisted and initialized asundefined.letandconstvariables are hoisted but NOT initialized; they reside in a "Temporal Dead Zone" (TDZ) until execution reaches their declaration. - βΊRe-assignment:
varandletallow re-assignment.constdoes not; it creates a read-only reference, though properties ofconstobjects/arrays can still be modified.
function scopeExample() {if (true) {var x = class="hl-number">10;let y = class="hl-number">20;const z = class="hl-number">30;}console.log(x); // 10 (function scoped)// console.log(y); // ReferenceError: y is not defined// console.log(z); // ReferenceError: z is not defined}
Mention "Temporal Dead Zone (TDZ)" and explain that block scope prevents accidental variables leak, which is a major benefit of let/const.