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! Ternarycondition ? 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

codeTap to expand ⛶
1// if / else if / else
2const score = 85;
3let grade;
4
5if (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"
15
16// Switch statement
17const 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}
33
34// Ternary for concise conditionals
35const age = 20;
36const canVote = age >= 18 ? "Yes" : "No";
37
38// Nested ternary (use sparingly!)
39const category = age < 13 ? "Child" : age < 20 ? "Teen" : "Adult";
40
41// 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:

  1. Write a function that takes a month number (1-12) and returns the season using switch
  2. Write a grading function using if/else that handles edge cases (negative scores, >100)
  3. Refactor a deeply nested if/else into guard clauses
  4. Write a FizzBuzz function using ternary operators only

⚠️ Common Mistakes

  • Forgetting break in switch — causes fall-through where subsequent cases execute

  • Using = instead of === in conditions — assignment vs comparison

  • Deeply 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.