Switch Statement for Multiple Cases in Javascript

Switch statements are a powerful tool in JavaScript that allow you to execute different blocks of code based on different conditions. However, what if you need to execute the same code for multiple cases? In this blog post, we will explore different ways to handle multiple cases in a switch statement in JavaScript.

Method 1: Repeating the same code

One straightforward way to handle multiple cases in a switch statement is to repeat the same code for each case. Although this method works, it can be repetitive and lead to code duplication. Here’s an example:


switch (fruit) {
  case 'apple':
    // code for apple
    break;
  case 'banana':
    // code for banana
    break;
  case 'orange':
    // code for orange
    break;
  case 'mango':
    // code for mango
    break;
  case 'kiwi':
    // code for kiwi
    break;
  // Repeat the same code for each case
  case 'grape':
    // code for grape
    break;
  case 'watermelon':
    // code for watermelon
    break;
  case 'pineapple':
    // code for pineapple
    break;
  // ...
}

Method 2: Grouping cases

To avoid code duplication, you can group multiple cases together and execute the same code for each group. This approach can make your code more concise and easier to maintain. Here’s an example:


switch (fruit) {
  case 'apple':
  case 'banana':
  case 'orange':
  case 'mango':
  case 'kiwi':
    // code for all these fruits
    break;
  case 'grape':
  case 'watermelon':
  case 'pineapple':
    // code for all these fruits
    break;
  // ...
}

Method 3: Using an array of cases

Another way to handle multiple cases in a switch statement is by using an array of cases. This approach allows you to define the cases in an array and loop through them to execute the code. Here’s an example:


const fruits = ['apple', 'banana', 'orange', 'mango', 'kiwi'];

for (const fruit of fruits) {
  switch (fruit) {
    case 'apple':
    case 'banana':
    case 'orange':
    case 'mango':
    case 'kiwi':
      // code for all these fruits
      break;
    // ...
  }
}

These are three different ways to handle multiple cases in a switch statement in JavaScript. Choose the method that best fits your code structure and requirements. Happy coding!


Posted

in

, ,

by

Tags:

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *