JavaScript provides three ways to declare variables.
They differ in scope, hoisting behavior, and re-declaration rules.
β 1. Scope
πΉ var → Function-scoped
if (true) {
var x = 10;
}
console.log(x); // 10 β (leaks outside block)
πΉ let → Block-scoped
if (true) {
let y = 20;
}
console.log(y); // ReferenceError β
πΉ const → Block-scoped
if (true) {
const z = 30;
}
console.log(z); // ReferenceError β
β 2. Hoisting
All three are hoisted, but behave differently.
πΉ var → hoisted with undefined
console.log(a); // undefined β
var a = 5;
πΉ let & const → hoisted but in Temporal Dead Zone (TDZ)
console.log(b); // ReferenceError β
let b = 10;
console.log(c); // ReferenceError β
const c = 15;
β Cannot be accessed before declaration
β 3. Re-declaration
πΉ var → allowed (dangerous)
var x = 1;
var x = 2; // allowed β
πΉ let → NOT allowed
let y = 1;
let y = 2; // Error β
πΉ const → NOT allowed
const z = 1;
const z = 2; // Error β
β 4. Re-assignment
πΉ var → allowed
var a = 10;
a = 20;
πΉ let → allowed
let b = 10;
b = 20;
πΉ const → NOT allowed
const c = 10;
c = 20; // Error β
β οΈ But objects & arrays can be mutated:
const user = { name: "Teekam" };
user.name = "TS"; // allowed β
π₯ Summary Table
| Feature | var |
let |
const |
|---|---|---|---|
| Scope | Function | Block | Block |
| Hoisting | Yes (undefined) | Yes (TDZ) | Yes (TDZ) |
| Re-declaration | β Allowed | β Not allowed | β Not allowed |
| Re-assignment | β Allowed | β Allowed | β Not allowed |
| Default use | β Avoid | β Use | β Use |
π― Short Interview Answer
varis function-scoped, hoisted withundefined, and allows re-declaration, which can cause bugs.letandconstare block-scoped, hoisted but placed in the Temporal Dead Zone, preventing access before declaration.letallows reassignment, whileconstdoes not, making them safer and preferred in modern JavaScript.
β Best Practice
β Use const by default
β Use let only when reassignment is required
β Avoid var in modern code