Wednesday, August 13, 2025

Here’s a simple diagram to visualize the difference between const, let, and var: csharp Copy Edit

 Scope & Reassignment in JS/TS


1️⃣ var

   - Function-scoped

   - Can be reassigned

   - Can be redeclared

   ┌───────────────┐

   │ function test │

   │   var x = 1   │

   │   x = 2 ✅    │

   │   var x = 3 ✅│

   └───────────────┘

   Outside function: x exists globally (hoisting!)


2️⃣ let

   - Block-scoped { ... }

   - Can be reassigned

   - Cannot be redeclared in same block

   ┌───────────────┐

   │ {             │

   │   let y = 1   │

   │   y = 2 ✅    │

   │   let y = 3 ❌│

   │ }             │

   └───────────────┘

   Outside block: y does NOT exist


3️⃣ const

   - Block-scoped { ... }

   - Cannot be reassigned

   - Cannot be redeclared

   ┌───────────────┐

   │ {             │

   │   const z = 1 │

   │   z = 2 ❌    │

   │   const z = 3 ❌│

   │ }             │

   └───────────────┘

   Outside block: z does NOT exist


No comments:

Post a Comment