Conditional Statements
📖 Concept
Conditional statements control the flow of your program based on conditions.
if/else — The most common. Checks a condition and runs code blocks accordingly.
else if — Chain multiple conditions.
switch — Compares a value against multiple cases. Uses strict equality (===). Don't forget break!
Ternary — condition ? ifTrue : ifFalse — great for simple conditionals in assignments.
🏠 Real-world analogy: Conditionals are like a GPS giving directions — "If you reach the intersection, turn left. Otherwise, continue straight. If you see a gas station, stop."
💻 Code Example
1// if / else if / else2const score = 85;3let grade;45if (score >= 90) {6 grade = "A";7} else if (score >= 80) {8 grade = "B";9} else if (score >= 70) {10 grade = "C";11} else {12 grade = "F";13}14console.log(grade); // "B"1516// Switch statement17const day = "Monday";18switch (day) {19 case "Monday":20 case "Tuesday":21 case "Wednesday":22 case "Thursday":23 case "Friday":24 console.log("Weekday");25 break;26 case "Saturday":27 case "Sunday":28 console.log("Weekend");29 break;30 default:31 console.log("Invalid day");32}3334// Ternary for concise conditionals35const age = 20;36const canVote = age >= 18 ? "Yes" : "No";3738// Nested ternary (use sparingly!)39const category = age < 13 ? "Child" : age < 20 ? "Teen" : "Adult";4041// Guard clause pattern (clean code)42function processUser(user) {43 if (!user) return "No user provided";44 if (!user.email) return "No email found";45 // Main logic here — no deep nesting!46 return `Processing ${user.email}`;47}
🏋️ Practice Exercise
Mini Exercise:
- Write a function that takes a month number (1-12) and returns the season using
switch - Write a grading function using if/else that handles edge cases (negative scores, >100)
- Refactor a deeply nested if/else into guard clauses
- Write a FizzBuzz function using ternary operators only
⚠️ Common Mistakes
Forgetting
breakin switch — causes fall-through where subsequent cases executeUsing
=instead of===in conditions — assignment vs comparisonDeeply nesting if/else instead of using guard clauses (early returns)
Overusing nested ternaries — makes code unreadable; use if/else for complex logic
Not considering all edge cases — e.g., what if the input is
null,undefined, or wrong type?
💼 Interview Questions
🎤 Mock Interview
Mock interview is powered by AI for Conditional Statements. Login to unlock this feature.