Anjan Dutta

Switch on ranges and multiple conditions in javascript

Switch on ranges and multiple conditions in javascript

updated on : 28/08/2021

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.

1let age = // user input age
2let userType = null;
3
4switch (true){
5
6 case age > 17 && age < 35:
7 userType = "Young Adult";
8 break;
9
10 case age < 55:
11 userType = "Middle-aged Adult";
12 break;
13
14 case age >= 55:
15 userType = "Older Adults";
16 break;
17
18 default:
19 userType = "Minor";
20}

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 based on the input. A continent has multiple countries, so we have to result in a single continent based upon any of those defined countries.

1let country = // get country
2let continent = null;
3
4switch(country){
5
6 case 'Germany':
7 case 'Italy':
8 case 'France':
9 continent = 'Europe';
10 break;
11
12 case 'India':
13 case 'China':
14 case 'Japan':
15 continent = 'Asia';
16 break;
17
18 case 'South Africa':
19 case 'Egypt':
20 case 'Mauritius':
21 continent = 'Africa';
22 break;
23
24 default:
25 continent = 'Not defined';
26}

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.