JavaScript Switch

The switch statement tests a variable against multiple values (cases) and executes code when a match is found. It's useful when you have many conditions for a single variable.

Key Topics

Basic switch

The switch statement compares an expression to case values and executes the matching case block.

let day = "Monday";
switch(day) {
    case "Monday":
        console.log("Start of the week");
        break;
    case "Friday":
        console.log("Almost weekend");
        break;
}

Output

> Start of the week

Explanation: Since day is "Monday", the first case matches and executes.

default Case

The default case executes if no other case matches.

let color = "Green";
switch(color) {
    case "Red":
        console.log("Stop");
        break;
    case "Yellow":
        console.log("Caution");
        break;
    default:
        console.log("Go");
}

Output

> Go

Explanation: Since "Green" doesn't match "Red" or "Yellow", the default case runs.

break Statement

break stops execution inside the switch. Without it, execution falls through to subsequent cases.

let fruit = "Banana";
switch(fruit) {
    case "Apple":
        console.log("Apple chosen");
        break;
    case "Banana":
        console.log("Banana chosen");
        // no break here, will fall through if another case follows
}

Output

> Banana chosen

Explanation: With no break, if another case existed after "Banana", it would also run. Typically, you use break to prevent this.

JavaScript Usage in DOM

Use switch to handle user inputs, such as menu selections or form choices, to determine which UI changes to apply.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Switch in DOM</title>
</head>
<body>
    <h1>Switch Demo</h1>
    <input type="text" id="choice" placeholder="Enter Apple or Banana">
    <button onclick="checkFruit()">Check</button>
    <p id="message"></p>

    <script>
        function checkFruit() {
            let input = document.getElementById("choice").value;
            switch(input) {
                case "Apple":
                    document.getElementById("message").textContent = "You chose Apple";
                    break;
                case "Banana":
                    document.getElementById("message").textContent = "You chose Banana";
                    break;
                default:
                    document.getElementById("message").textContent = "Unknown fruit";
            }
        }
    </script>
</body>
</html>

Key Takeaways

  • switch: Compare one value against multiple cases.
  • default: Handle unmatched cases.
  • break: Prevent execution from falling through to next case.
  • DOM Integration: Respond to user inputs with structured decision logic.