Optimizing the switch Statement in JavaScript

William Le

The switch statement is indispensable for certain programming tasks. In this article, you’ll learn how to use switch and hopefully gain the intuition to know when you should use it.

A telltale sign to use switch is when you have a lot of consecutive if/else statements. Let’s look at an example using if/else, and then we’ll look at the switch equivalent for comparison:

let dayIndex = new Date().getDay();
let day;

if (dayIndex === 0) {
  day = 'Sunday';
}
else if (dayIndex === 1) {
  day = 'Monday';
}
else if (dayIndex === 2) {
  day = 'Tuesday';
}
else if (dayIndex === 3) {
  day = 'Wednesday';
}
else if (dayIndex === 4) {
  day = 'Thursday';
}
else if (dayIndex === 5) {
  day = 'Friday';
}
else if (dayIndex === 6) {
  day = 'Saturday';
};

console.log(day); // "Friday"

Did you know? JavaScript doesn't have a native method to get the day of the week!

Using if/else is really verbose, and contains a lot of unnecessary boilerplate that switch can handle with ease:

let dayIndex = new Date().getDay();
let day;

switch (dayIndex) {
  case 0:
    day = "Sunday";
    break;
  case 1:
    day = "Monday";
    break;
  case 2:
    day = "Tuesday";
    break;
  case 3:
    day = "Wednesday";
    break;
  case 4:
    day = "Thursday";
    break;
  case 5:
    day = "Friday";
    break;
  case 6:
    day = "Saturday";
    break;
};

console.log(day); // "Friday"

There’s barely any code, and it’s refreshingly minimal. This is because switch places emphasis on the possible values instead of the conditions for the values.

Using break

Since JavaScript will navigate through the entire case branch many times it’s advisable to use break to prevent unexpected case matches or to save the engine from having to parse extra code.

switch (dayIndex) {
  case 0:
    day = "Sunday";
    break;
  case 1:
    day = "Monday";
    break;
  case 2:
    day = "Tuesday";
    break;
  case 3:
    day = "Wednesday";
    break;
  case 4:
    day = "Thursday";
    break;
  case 5:
    day = "Friday";
    break;
  case 6:
    day = "Saturday";
    break;
}

In this example, break doesn’t actually provide any added safety since case 2 can never be case 5 (for example) so break is somewhat extraneous. This rigorous usage of break seems to be a preferential matter among developers like the usage of semicolons (;). Developers that take an explicit approach to programming will use break for every case, while some developers only use break strategically in switch. There’s a slight performance gain from using it across the board however, because even if there’s no chance for another case to be true, at least you won’t even have the engine run through the rest of the switch statement.

The Strategic Use of “break”

Sometimes you’ll actually want your cases to “fall through”. Using break for these instances is more of a strategy than a safety measure.

let seasonIndex = new Date().getMonth();
let season;

switch (seasonIndex) {
  case 0:
  case 1:
  case 2:
    season = 'Winter'; // January, February, March
    break;
  case 3:
  case 4:
  case 5:
    season = 'Spring'; // April, May, June
    break;
  case 6:
  case 7:
  case 8:
    season = 'Summer'; // July, August, September
    break;
  case 9:
  case 10:
  case 11:
    season = 'Autumn'; // October, November, December
    break;
}

In this example, the cases are “falling through” and break is used to explicitly exit switch early. This allows you to lump several cases together with a single value.

The if/else version would require using lots of || logical operators which doesn’t seem as transparent:

 if (seasonIndex === 0 || seasonIndex === 1 || seasonIndex === 2) {
   season = 'Winter';
 } else if (seasonIndex === 3 || seasonIndex === 4 || seasonIndex === 5) {
   season = 'Spring';
 } else if (seasonIndex === 6 || seasonIndex === 7 || seasonIndex === 8) {
   season = 'Summer';
 } else if (seasonIndex === 9 || seasonIndex === 10 || seasonIndex === 11) {
   season = 'Fall';
 }

Handling Default Cases

Another feature of switch is the ability to handle unexpected or generic cases. Returning to our first example, we can use default to implement error handling:

let dayIndex = new Date().getDay();
let day;

switch (dayIndex) {
  default:
    day = new Error('Invalid argument: "dayIndex" must be an integer from 0 –> 6');
  case 0:
    day = 'Sunday';
    break;
  case 1:
    day = 'Monday';
    break;
  case 2:
    day = 'Tuesday';
    break;
  case 3:
    day = 'Wednesday';
    break;
  case 4:
    day = 'Thursday';
    break;
  case 5:
    day = 'Friday';
    break;
  case 6:
    day = 'Saturday';
    break;
}

You might have noticed that the default case is placed at the top. Not to worry! It’ll work as expected because JavaScript will look through all the case branches before it settling on default.

You can also use default for your generic cases:

let beverage = 'Mr. Pibb';
let cost;

switch (beverage) {
  default:
    cost = 0.05;
  case 'Pepsi':
    cost = 1.00;
    break;
  case 'Coca-Cola':
    cost = 1.00;
    break;
  case 'Dr. Pepper':
    cost = 2.00;
    break;
  case 'Moutain Dew':
    cost = 5.00;
    break;
}

console.log(cost); // 0.05

This ensures you’ll get some sorta value from switch even if it doesn’t match any of your defined cases.

Conclusion

Switch statements are an elegant alternative when you find yourself writing a lot of consecutive if/else statements. Even though you may not use switch as often as, say, a for-loop there’s no substitute when you need it. Modern libraries libraries like Lodash and Redux still use switch today, making it one of those old-school workhorse features of JavaScript you’ll always need to keep under your belt.

To learn more about switch visit the Mozilla Developer website.

  Tweet It

🕵 Search Results

🔎 Searching...

Sponsored by #native_company# — Learn More
#native_title# #native_desc#
#native_cta#