Control Flow: if, else if, switch & Guard Clauses
1. Simple Definition
Control Flow ka matlab hai program ke execution ka rasta tay karna. Default me code line-by-line upar se niche chalta hai. Lekin conditions (if, else if, else, switch) ke zariye hum computer ko decision lene dete hain ki agar condition TRUE ho toh rasta A chuno, agar FALSE ho toh rasta B chuno!
2. Real-Life Analogy
Chauraha par lagi traffic light:
• if: Batti RED hai? → Gaadi roko (Stop).
• else if: Batti YELLOW hai? → Gaadi slow karo aur prepare raho.
• else: Batti GREEN hai! → Gaadi aage badhao (Go!).
3. Why Do We Need It?
Authentication ("Kya password sahi hai?"), Ecommerce ("Kya product stock me hai?"), aur UI states ("Kya user ne dark mode chalu kiya hai?") ke sabhi smart decisions conditional statements par depend karte hain.
4. Syntax
// 1. if - else if - else
if (condition1) {
// Runs if condition1 is true
} else if (condition2) {
// Runs if condition2 is true
} else {
// Fallback if none match
}
// 2. switch - case
switch (expression) {
case "admin":
console.log("Full Access");
break; // Break zaroori hai!
case "editor":
console.log("Edit Access");
break;
default:
console.log("View Only");
}
5. Basic Example (Guard Clauses Pattern)
// Professional Guard Clause Pattern (Early Return)
function processOrder(isLoggedIn, hasFunds, inStock) {
// Deep nesting (Pyramid of Doom) se bachne ke liye pehle fail cases return karein:
if (!isLoggedIn) return "Pehle Login Karein!";
if (!inStock) return "Item Out of Stock hai!";
if (!hasFunds) return "Wallet me paise kam hain!";
// Agar sab theek hai toh main success flow
return "Order Successfully Placed! 🎉";
}
console.log(processOrder(true, true, true));
6. Output / Expected Result
7. Code Explanation
if (condition): Bracket ke andar ki condition truthy hone par hi block execute hota hai.switch-case: Jab ek hi variable ko 4 ya 5 exact values ke sath compare karna ho (e.g. days of week, user roles).break: Switch statement ko turant rok deta hai taaki niche wale cases unintentionally execute na hon.- Guard Clause: Badi if-else chains ke badle function ke shuru me hi invalid conditions check karke
returnkar dena (Industry clean code standard!).
8. Real-World Example
Netflix subscription gate: agar user ka plan 'premium' hai toh 4K video render karo, agar 'basic' hai toh 720p stream karo, aur agar expired hai toh payment modal popup dikhao.
9. Common Mistakes
Agar aap case ke aakhri me break; nahi likhte, toh agla case chahe match ho ya na ho, browser use bhi execute kar deta hai! (Jise Fallthrough kehte hain).
10. Best Practices
- Deeply nested
if { if { if { ... } } }likhne se bachein; Guard Clauses use karein. - Simple binary choices ke liye
if-elseke badle clean Ternary Operator (? :) use karein.
11. Try It Yourself
Playground me student ke marks (0-100) ke aadhar par Grade ("A", "B", "C", "Fail") calculate karne wala if-else if block banayein.
12. Challenge
Ek Day Planner banayein jo switch(day) se Monday ko "Workday", Saturday ko "Party", aur Sunday ko "Chill" print kare.
13. Interview Questions
Answer: Jab conditions complex expressions ya ranges hon (jaise age >= 18 && score < 50), tab if-else best hai. Jab ek hi discrete variable ko specific fixed values (jaise role === 'admin', 'guest', 'user') ke against match karna ho, tab switch zyada readable aur optimize hota hai.
14. Quick Revision
if / else if / elseruns based on truthy evaluation.- Always put
break;in switch cases. - Guard clauses eliminate nested clutter.
15. FAQ
Q1. Kya if condition ke bina curly braces {} chal sakti hai?
Agar sirf single line code ho toh bina {} chal sakti hai, lekin production code me bugs se bachne ke liye hamesha curly braces compulsory mane jaate hain.
Q2. switch-case me default case kyu lagate hain?
Agar upar ka koi bhi case match na ho toh fallback safe response dene ke liye.
Q3. switch case me strictly check hota hai ya loosely?
Switch hamesha Strict Equality (===) se match karta hai (No type coercion).
Q4. Truthy aur Falsy me if condition kaise behave karti hai?
if ("hello") true maana jayega kyunki non-empty string truthy hoti hai.
Q5. Guard clause performance kaise improve karta hai?
Unnecessary heavy logic run hone se pehle hi function exit kar deta hai.
Control Flow: if, else if, switch & Guard Clauses
1. Simple Definition
Control Flow dictates the execution path your program takes based on dynamic conditions. Common constructs include if / else if / else, switch statements, and the modern architectural pattern of Guard Clauses (Early Return) to eliminate nested conditional pyramids.
2. Real-Life Analogy
Instead of checking a traveler through 5 nested security rooms simultaneously, the first checkpoint checks: "No boarding pass? Turn around immediately!" (Guard clause). Only passengers meeting every prerequisite reach the final boarding gate!
3. The Guard Clause Pattern (Early Return)
// ❌ Bad Practice: Deep Nested "Arrow Anti-Pattern"
function processPayment(user, cart) {
if (user) {
if (user.isVerified) {
if (cart.length > 0) {
return chargeCard(user, cart);
} else {
return "Cart is empty";
}
} else {
return "User not verified";
}
} else {
return "User not logged in";
}
}
// ✅ Clean Production Code: Clean Guard Clauses
function processPayment(user, cart) {
if (!user) return "User not logged in";
if (!user.isVerified) return "User not verified";
if (cart.length === 0) return "Cart is empty";
return chargeCard(user, cart);
}
4. Switch Statements vs Object Lookup Tables
// Modern Clean Alternative to Switch: Lookup Dictionary
const rolePermissions = {
admin: "Full Access",
editor: "Edit & Publish",
viewer: "Read Only",
};
const userRole = "editor";
const permission = rolePermissions[userRole] ?? "No Access";
5. Common Mistakes
Omitting break in a switch statement causes execution to fall through and execute subsequent cases unintentionally!
6. Best Practices
- Prefer guard clauses (early returns) over deep if/else nesting.
- Use dictionary/object lookups in place of bloated 10-case switch statements.
- Keep conditional tests explicit and readable.
7. Practice Exercise
Refactor a nested authentication function into a clean guard clause structure that checks for valid token, valid role, and active session.
8. Interview Questions
Answer: Guard clauses reduce cognitive complexity, keep indentation flat, isolate error conditions immediately at the top of functions, and keep primary business logic linear and easy to follow.
9. Summary / Cheat Card
- Guard clauses exit early when prerequisites fail.
- Object lookups provide elegant alternatives to switch blocks.
- Never nest conditionals more than 2 levels deep.
10. FAQ
Q1. Can you return without a value in JavaScript?
Yes, calling return; exits the function immediately, returning undefined.