HTML CSS Bootstrap JavaScript jQuery MySQL PHP Data Mining

JavaScript Switch

The switch statement is used to perform different actions based on different conditions. It is a more organized alternative to using multiple if...else if statements when you have many potential matches for a single value.


Syntax

switch(expression) {
  case x:
    // code block
    break;
  case y:
    // code block
    break;
  default:
    // code block
}

How it Works

  1. The switch expression is evaluated once.
  2. The value of the expression is compared with the values of each case.
  3. If there is a match, the associated block of code is executed.
  4. The break keyword breaks out of the switch block and stops the execution.
  5. The default keyword specifies the code to run if there is no case match.

The break Keyword

When JavaScript reaches a break keyword, it breaks out of the switch block. This will stop the execution inside the block. If you forget to use break, the next case will be executed even if the evaluation does not match the case (this is called "fall-through").


Common Code Blocks

Sometimes you will want different switch cases to use the same code. You can group them like this:

switch (new Date().getDay()) {
  case 4:
  case 5:
    text = "Soon it is Weekend";
    break;
  case 0:
  case 6:
    text = "It is Weekend";
    break;
  default:
    text = "Looking forward to the Weekend";
}
Important: Switch cases use Strict Comparison (===). The values must be of the same type to match. A string "7" will not match a number 7.

Key Points to Remember

  • Use switch for multi-way branching based on a single value
  • Each case must end with a break to avoid fall-through
  • The default case handles unsupported values (fallback)
  • Comparison is strict (===)—types matter!
  • Code is cleaner and more readable than long if-else chains
  • If multiple cases match, ONLY the first one is executed