javascript

Switch on ranges and multiple conditions in javascript

Switch cases are easy to use and great for writing clean code. It takes one input and matches that input value with the defined cases inside the switch body.

The ideal scenario is to use different operations for different switch cases. But often we get problems where we need to run the same code for multiple conditions. Or, sometimes it can be ranges of integers for which we need to run a generic block of code.

Today, I am going to discuss these two scenarios.

  • Switch on ranges of integers
  • Switch on multiple conditions in javascript

Switch on ranges of integers

Below is a case for categorizing a user as young, middle-aged or adult based upon their age.

 let age = // user input age
 let userType = null;

 switch (true){

     case age > 17 && age < 35:
        userType = "Young Adult";
         break;    

     case age < 55:
        userType = "Middle-aged Adult";
         break;

     case age >= 55:
          userType = "Older Adults";
         break;

     default:
         userType = "Minor";
 } 

If the number of cases is less, then an if-else condition is preferable for simplicity.

Switch on multiple conditions in javascript

We can implement the above problem using this method. But, this method can result in redundant code.

Below is a sample code to determine the continent of a country. A continent has multiple countries, so we have to result in a single continent based upon any of those defined countries.

 let country = // get country
 let continent = null;

 switch(country){

     case 'Germany':
     case 'Italy':
     case 'France':
         continent =  'Europe';
         break;

     case 'India':
     case 'China':
     case 'Japan':
         continent =  'Asia';
         break;

     case 'South Africa':
     case 'Egypt':
     case 'Mauritius':
          continent =  'Africa';
          break;

     default:
         continent =  'Not defined';
 } 

How does it work

In the above example, we are using empty cases, and it is perfectly alright to do so. When control flow enters the switch body, it checks for a matching scenario.

On finding a match, it continues to execute the next lines of code until it gets a break statement.

The placement of the break is significant here, and we often end up making mistakes.

These are the little tricks we can use to solve much bigger problems. But before choosing any of the above methods, we must consider the feasibility of using if-else or any other option if available.

Leave a Comment

seventy seven − seventy five =