JavaScript Switch Case

JavaScript Switch Case

The switch statement in JavaScript is used to execute different blocks of code based on the value of a variable or expression. It is an alternative to multiple if...else if statements when you are checking for multiple specific values.

Syntax:

  switch (expression) {
    case value1:
        // Code to execute if expression === value1
        break;
    case value2:
        // Code to execute if expression === value2
        break;
    // Add more cases as needed
    default:
        // Code to execute if none of the cases match
}

How it Works:

  • The expression is evaluated once.
  • The value of the expression is compared with each case value.
  • If a match is found, the code for that case is executed.
  • The break statement prevents the code from falling through to the next case.
  • The default case (optional) runs if no other case matches.

Example:

  let day = 3;

  switch (day) {
      case 1:
          console.log("Monday");
          break;
      case 2:
          console.log("Tuesday");
          break;
      case 3:
          console.log("Wednesday");
          break;
      case 4:
          console.log("Thursday");
          break;
      case 5:
          console.log("Friday");
          break;
      default:
          console.log("Weekend");
  }

Explanation:

  • The value of day is 3.
  • The switch statement compares day to each case:
    • It does not match 1 or 2.
    • It matches 3, so "Wednesday" is printed.
  • The break prevents execution from continuing to the next cases.

Output:

Wednesday


Example with No break:

If you omit the break, execution will continue into the next case(s) until a break or the end of the switch.

  function categorizeNumber(num) {
    let result = "";

    switch (num) {
        case 1:
            result += "One ";
        case 2:
            result += "Two ";
        case 3:
            result += "Three ";
        default:
            result += "Number or higher";
    }

    return result.trim();
  }

  console.log(categorizeNumber(1)); // Output: "One Two Three Number or higher"
  console.log(categorizeNumber(2)); // Output: "Two Three Number or higher"
  console.log(categorizeNumber(3)); // Output: "Three Number or higher"
  console.log(categorizeNumber(4)); // Output: "Number or higher"
	

Explanation::

  • No break statements: Once the code enters a case, all subsequent cases (including default) are executed, regardless of whether they match or not.
  • Result:
    • For num = 1, it starts at case 1 and continues through all cases and default.
    • For num = 2, it starts at case 2 and continues through the remaining cases.
    • For num = 4, it skips all cases and only executes default.

To avoid this "fall-through" behavior, always use break unless it's intentional.


Example with default:

In JavaScript, a switch statement is used to perform different actions based on different conditions. The default case in a switch statement is executed if none of the specified case values match the provided expression. It acts as a fallback option.

Key Points:

  • The break statement prevents the execution from falling through to subsequent cases.
  • If no case matches and a default statement is present, the default block will execute.

Example:

Here's an example that determines the type of a day based on a numeric input:

  const dayNumber = 5;

  switch (dayNumber) {
    case 1:
      console.log("Monday - Start of the workweek!");
      break;
    case 2:
      console.log("Tuesday");
      break;
    case 3:
      console.log("Wednesday - Midweek");
      break;
    case 4:
      console.log("Thursday");
      break;
    case 5:
      console.log("Friday - Almost weekend!");
      break;
    case 6:
      console.log("Saturday - Weekend!");
      break;
    case 7:
      console.log("Sunday - Relax and recharge!");
      break;
    default:
      console.log("Invalid day number. Please enter a number between 1 and 7.");
  }
	

Explanation:

  • dayNumber is the input expression being evaluated.
  • If dayNumber matches 1, 2, etc., the corresponding case block runs, and the break ensures no further cases execute.
  • If dayNumber doesn't match any case, the default block executes to handle invalid inputs.

Output:

If dayNumber is 5, the output will be:

Friday - Almost weekend!

If dayNumber is 8, the output will be:

Invalid day number. Please enter a number between 1 and 7.

Previous Next