How to optimize the switch statement in JavaScript ?

The switch statement is necessary for certain programming task and the functionality of switch statement is same among all programming language. Basically switch statements switch the cases as per the desire condition is given to the switch. Switch statement can be used when multiple number of consecutive if/else statement is in use. But somewhere if/else statement is beneficial to use and somewhere switch statement. So, we are given to optimize the switch statement in the programming task in JavaScript.

Since JavaScript will navigate through the entire case branch many times it’s advisable to use the break to prevent unexpected case matches or to save the engine from having to parse extra code. There are lots of ways to use break according to the situation like for season checking there is more than one month that comes into a particular season and for that condition break can be used somewhere else according to the situation.

Now take an example to understand the switch statement. Here we are trying to get the weekdays using the switch.
Here, Two cases are available for comparison:



  • If/Else Statement.
  • Switch Statement.

Below examples implements the both approaches:

Example 1:

filter_none

edit
close

play_arrow

link
brightness_4
code

<script>
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"
</script>

chevron_right


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

filter_none

edit
close

play_arrow

link
brightness_4
code

<script>
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"
</script>

chevron_right


Note: JavaScript doesn’t have a native method to get the day of the week

full-stack-img




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.