Topic 02 / 11

Variables, let, const & Block Scope

1. Simple Definition

Variable memory ke andar ek labeled storage dabba hota hai jisme hum koi value (data) temporarily store karke rakhte hain taaki baad me use ya modify kar sakein. Modern JavaScript (ES6+) me variables declare karne ke liye const (constant/fixed) aur let (reassignable) use hota hai. Puraane var ko legacy bugs ki wajah se ab use nahi kiya jata.

2. Real-Life Analogy

🔒 Digital Locker vs Whiteboard vs Puraana Leaky Dabba

const (Locked Locker): Ek baar jo saman rakh kar lock kar diya, use change nahi kar sakte (jaise aapka Aadhar card number ya Birthday).
let (Whiteboard): Scoreboard jahan abhi score 10 hai, naya chhakka laga toh purana mita kar 16 likh diya (Value can change).
var (Puraana Leaky Dabba): Ek aisa tuta dabba jo room ke bahar tak leak karta hai aur achanak bina bataye memory me upar uth jata hai (Hoisting bugs).

3. Why Do We Need It?

Bina variables ke program user ka name, cart ka total price, ya login status yaad hi nahi rakh payega. Variables dynamic state ka foundation hain.

4. Syntax & Comparison

// 1. const: Re-assignment strictly NOT allowed
const appName = "WebDev Hinglish";
// appName = "New Name"; // ❌ TypeError: Assignment to constant variable.

// 2. let: Value can be updated
let userScore = 0;
userScore = userScore + 10; // ✅ Allowed!

// 3. var: The Legacy Culprit (Never use in new code!)
var legacyBug = "Avoid me!";

5. Basic Example (Scope Demonstration)

// Global Scope
const globalUser = "Rahul";

if (true) {
  // Block Scope (Curly brackets { ... } ke andar)
  let secretCode = 1234;
  const insideBlock = "Main sirf is block me zinda hoon!";
  console.log(globalUser); // ✅ Rahul
  console.log(secretCode); // ✅ 1234
}

// console.log(secretCode); 
// ❌ ReferenceError: secretCode is not defined (Block scope protected!)

6. Output / Expected Result

> "Rahul"
> 1234
> Uncaught ReferenceError: secretCode is not defined

7. Code Explanation

  • const: Default choice hona chahiye. Isse accidental bugs nahi aate.
  • let: Sirf tab use karein jab variable ki value future me re-assign karni ho (jaise loops ka let i = 0 ya counters).
  • Block Scope: let aur const kisi bhi { ... } block (if, for, while) ke bahar leak nahi hote.
  • Hoisting & TDZ: let aur const hoist hote hain lekin unhe initialization se pehle access karne par Temporal Dead Zone (TDZ) ki wajah se ReferenceError milta hai (jo ki acchi baat hai!).

8. Real-World Example: Shopping Cart Total

const TAX_RATE = 0.18; // 18% GST (Never changes -> const)
let cartTotal = 999;   // Can change when items are added -> let

cartTotal = cartTotal + 499; // Adding another t-shirt
const finalAmount = cartTotal + (cartTotal * TAX_RATE);
console.log("Total Payable:", finalAmount);

9. Common Mistakes

⚠️ Galti 1: const me array/object modify na hona samajhna

const user = { name: "Amit" } me aap user = ... reassign nahi kar sakte, lekin user.name = "Vikram" property modify kar sakte hain! const variable ka reference lock karta hai, andar ka data nahi.

⚠️ Galti 2: var use karke variable leak kar dena

for (var i = 0; i < 5; i++) { ... } likhne par i loop khatam hone ke baad bhi poore program me zinda rehta hai. Hamesha let i = 0 use karein!

10. Best Practices

  • Golden Rule: Hamesha pehle const likhein. Jab actually reassign karne ki zarurat pade, tabhi use let banayein.
  • Variables ke descriptive camelCase names rakhein (jaise userEmailAddress, isLoading).

11. Try It Yourself

Playground me const birthYear = 2004; banayein aur usme birthYear = 2005; reassign karke error observe karein.

12. Challenge

Ek age-checker block banayein jisme const userAge = 19; ho aur if block ke andar let isEligible = true; define ho.

13. Interview Questions

💼 Q: let, const aur var me 3 sabse bade differences kya hain?

Answer:
1. Scope: var function-scoped hota hai; let aur const block-scoped hote hain.
2. Re-declaration: var ko same scope me dobara declare kar sakte hain (bug prone); let/const syntax error dete hain.
3. Hoisting & TDZ: var hoist hokar undefined deta hai; let/const Temporal Dead Zone me rehte hain aur access karne par ReferenceError dete hain.

14. Quick Revision

  • Default: const.
  • When changing: let.
  • Never: var.
  • Block Scope = Safe Scope.

15. FAQ

Q1. Temporal Dead Zone (TDZ) kya hota hai?

Block ke shuru hone se lekar variable declare hone tak ka time-zone jisme variable ko touch karne par error milta hai.

Q2. Bina let ya const likhe variable banana kaisa hai?

x = 10; likhne par wo window object par global leak ban jata hai. "use strict"; mode me ye illegal error hota hai.

Q3. CamelCase kya hota hai?

Pehla word lowercase aur aage ke words ka pehla letter capital (jaise: myFirstName).

Q4. Kya const array me .push() kar sakte hain?

Haan! const arr = [1, 2]; arr.push(3); bilkul valid hai kyunki array reference change nahi hua.

Q5. Hoisting ka kya matlab hai?

Browser execution se pehle variable declarations ko scope ke top par memory me reserve kar leta hai.

Topic 02 / 11

Variables, let, const & Block Scope

1. Simple Definition

In JavaScript, a Variable is a labeled storage container in memory used to hold data values. Modern JavaScript (ES6+) provides three variable declarations: const (for values that must not be reassigned), let (for mutable values whose values change over time), and the legacy keyword var (which is avoided in modern software due to scope hoisting flaws).

2. Real-Life Analogy

📦 Labeled Plastic Tupperware vs Permanent Engraved Plate

let: A plastic lunchbox with a dry-erase sticker label. Today you put noodles inside; tomorrow you erase it and pack sandwiches (reassignable value).
const: A government passport number permanently etched into biometric plastic—once created, the identification number can never be erased or swapped!

3. Comparison: var vs let vs const

Feature var (Legacy 1995) let (Modern ES6) const (Modern ES6)
Scope Function Scoped Block Scoped {} Block Scoped {}
Reassignment Yes Yes ❌ No (Throws TypeError)
Redeclaration Yes (Dangerous bug source) ❌ No ❌ No
Hoisting Behavior Hoisted as undefined Temporal Dead Zone (TDZ) Temporal Dead Zone (TDZ)

4. Syntax & Basic Usage

// 1. const: Default choice for constants
const API_URL = "https://api.example.com/users";
const taxRate = 0.18;

// 2. let: Used when values mutate (counters, toggles)
let score = 0;
score = score + 10; // Perfectly valid

// 3. Block Scope demonstration
if (true) {
  let blockVariable = "Only accessible inside these braces!";
  const secretKey = 999;
}
// console.log(blockVariable); // ReferenceError: blockVariable is not defined

5. Common Mistakes

⚠️ Common Pitfall: Reassigning const vs Mutating Objects

const prevents variable reassignment (user = ... is prohibited). However, the internal properties of a const object or array can be mutated (user.age = 26 is valid)! To prevent mutation, use Object.freeze().

6. Best Practices

  • Rule of Thumb: Always default to const. Only switch to let when you know a variable must be reassigned (e.g. loops or accumulators).
  • Never use var in modern codebases.
  • Use descriptive camelCase for variable names (e.g. userCartTotal).

7. Practice Exercise

🎯 Exercise: Variable Swapping Logic

Declare two variables: let a = 5; let b = 10;. Swap their values so that a holds 10 and b holds 5 (Bonus: accomplish this using modern destructuring [a, b] = [b, a]).

8. Interview Questions

💼 Q: What is the Temporal Dead Zone (TDZ) in JavaScript?

Answer: The TDZ is the period of execution between the start of a block scope and the line where a let or const variable is declared. Accessing the variable within the TDZ throws a ReferenceError rather than returning undefined.

9. Summary / Cheat Card

  • const by default; let when reassigning. Never var.
  • let and const respect block scope {}.
  • TDZ prevents reading variables prior to their declaration.

10. FAQ

Q1. Can you declare a const without an initial value?

No. const x; will throw a SyntaxError: Missing initializer in const declaration.

Q2. Does block scope apply inside if statements and for loops?

Yes! Any pair of curly brackets { ... } creates a distinct block scope for let and const.