Master AI & Build your First Coding Portfolio with SkillReactor | Sign Up Now

3 Conditional Structures

4 Switch Statement

The switch statement is a conditional structure similar to if-else. But why do we need a switch statement? The primary reason for using a switch statement is to simplify code readability and organization, especially when dealing with multiple possible cases or conditions.

You can think of the switch statement like a food menu that lists several food items. You can pick one and order it. Similarly, the switch statement evaluates an expression and executes different blocks of code based on its label or value. It compares the expression against multiple cases and executes the code associated with the first matching case. If no match is found, an optional default case can be executed.

The syntax for the switch statement is almost the same in various programming languages:

switch (expression) {
  case value1:
    // Code to execute if expression equals value1
    break;
  case value2:
    // Code to execute if expression equals value2
    break;
  // Additional cases
  default:
    // Code to execute if no case matches the expression (optional)
}

JavaScript Example

let day = "Monday";

switch (day) {
  case "Monday":
    console.log("Start of the work week!");
    break;
  case "Tuesday":
  case "Wednesday":
  case "Thursday":
    console.log("Midweek grind.");
    break;
  case "Friday":
    console.log("TGIF!");
    break;
  default:
    console.log("Enjoy the weekend!");
}

In this example:

  • The variable day is set to "Monday".
  • The switch statement evaluates day.
  • Since day is "Monday", it matches the first case, and "Start of the work week!" is printed.
  • The break statement exits the switch statement after execution.

This construct provides a structured way to handle multiple conditions based on the value of an expression.