Open In App
Related Articles

How to optimize the switch statement in JavaScript ?

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Report issue
Report

The switch statement is necessary for certain programming tasks and the functionality of the switch statement is the same among all programming languages. Basically switch statements switch the cases as per the desired condition given to the switch. A switch statement can be used when multiple numbers 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:

Below are examples implementing both approaches: 

Example 1: This example demonstrates the if/else statement in Javascript.

javascript

<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>

                    

Output:

Friday

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

javascript

<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>

                    

Output:

Friday

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



Last Updated : 06 Feb, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads