← Back to Engine

0.3 Control Flow: `if`, `else` & `switch`


Control flow allows your code to make decisions. Depending on whether conditions evaluate to true or false, different code blocks are executed.

1. Strict Comparison (`===`) vs Loose (`==`)

Always compare values using strict equality ===:

  • 5 === "5"false (Checks value AND data type!)
  • 5 == "5"true (Coerces string to number — dangerous!)

2. `if`, `else if`, and `else`

let score = 85;

if (score >= 90) { 
    console.log("Grade: A");  
} else if (score >= 80) { 
    console.log("Grade: B"); 
} else { 
    console.log("Grade: C"); 
} 

3. Ternary Operator (`condition ? a : b`)

A concise one-line shorthand for simple if/else decisions:

let age = 20;
let status = (age >= 18) ? "Adult" : "Minor";

4. Multi-Branch Decisions with `switch`

When comparing a single variable against multiple exact values, switch is cleaner than multiple else if blocks:

let day = "Monday"; 

switch (day) { 
    case "Monday": 
        console.log("Start of week!"); 
        break; // Exits switch block
    case "Friday":
        console.log("Weekend is near!");
        break;
    default:
        console.log("Mid-week day");
}

📌 KEY POINTS TO REMEMBER

  • Always use `===` instead of `==` to prevent unintended type conversion.
  • Remember `break` in `switch`: Forgetting `break;` causes execution to "fall through" into the next case regardless of whether it matches.
  • The 6 Falsy Values: false, 0, "" (empty string), null, undefined, and NaN. Every other value in JavaScript is Truthy.

⚡ Interactive Visual: Switch Signal Router

Select a traffic light signal to inspect which switch branch executes:

Click a signal button above.