Let’s make it super clear by comparing var, let, and const in JavaScript.


πŸ“Š var vs let vs const

Featurevarletconst
ScopeFunction-scopedBlock-scoped { }Block-scoped { }
Hoistingβœ… Hoisted (initialized as undefined)βœ… Hoisted (but TDZ β†’ error if accessed before declaration)βœ… Hoisted (but TDZ β†’ error if accessed before declaration)
Redeclarationβœ… Allowed❌ Not allowed❌ Not allowed
Reassignmentβœ… Allowedβœ… Allowed❌ Not allowed
InitializationOptional (defaults to undefined)OptionalMandatory (must assign a value)
Use in LoopsProblematic (no block scope)SafeSafe
Best Use CaseOld/legacy codeVariables that may changeConstants / Fixed values

πŸ”Ή Examples

1️⃣ var Example (Function-scoped, Redeclarable)

var x = 10;
var x = 20;   // βœ… Redeclaration allowed
console.log(x); // 20

⚠ Problem: It leaks outside block scope

if (true) {
  var city = "Delhi";
}
console.log(city); // βœ… Works (not block-scoped, unsafe)

2️⃣ let Example (Block-scoped, Reassignable)

let age = 20;
age = 21;      // βœ… Reassignment allowed
// let age = 22; ❌ Error (no redeclaration in same scope)
console.log(age); // 21

Safe in loops:

for (let i = 0; i < 3; i++) {
  setTimeout(() => console.log(i), 1000);
}
// βœ… Output: 0, 1, 2

3️⃣ const Example (Block-scoped, Fixed Reference)

const PI = 3.14159;
// PI = 3.15; ❌ Error (cannot reassign)
console.log(PI); // 3.14159

But objects/arrays inside const can still be modified:

const person = { name: "Raj", age: 20 };
person.age = 21; // βœ… Allowed
// person = {};   ❌ Error (cannot reassign object reference)
console.log(person); // { name: 'Raj', age: 21 }

🎯 Real-Life Analogy

  • var β†’ Old container with holes (not safe, things leak out).
  • let β†’ New box you can reopen and change items inside.
  • const β†’ Sealed box, you cannot replace it, but you can rearrange items inside (for objects/arrays).

βœ… Which One Should You Use?

  • Use const by default.
  • Use let if you know the value will change.
  • Avoid var (only for legacy/old code).

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *