Using the JavaScript Switch Statement 👨‍💻🔃 (with Examples)

switch-control-panelA few weeks ago I wrote an article on the C# Switch statement, demonstrating some of the switch statement basics and features C# adds to the statement. Today I am sharing a similar article on how the switch statement works in JavaScript.

Use the switch statement to execute one of many code blocks based on a variable or expression's value. The switch expression is evaluated once. The comparision value will match either a statement value or trigger a default code block.

Switch statement is used as an alternate to multiple if .. else statements. Switch statements are a more efficient way to code when testing multiple conditions.

  • This case statement is used to execute various actions for various conditions or variable states
  • Use the Switch Case statement to pick a block of code to execute
  • The Switch statement uses strict comparisons (===), values must be the same type to match

State switch statement works like this:

  • The switch expression is evaluated once
  • The value of the expression is compared with the values of each case
  • If there is a match, the associated block of code is executed
  • A default or catch all case can be defined when the expression does not match a case.

The basic JavaScript switch syntax:


switch(expression)
{
    case value:
        expression;
        break;

    case value:
        expression;
        break;

    default:
        Expression;

}

Following the logic of the example syntax, this sequence of events take place.

  • The expression is evaluated
  • The first case is tested against the expression.
  • If the case matches the expression value the code executes
  • the break keyword ends the switch block.
  • If the case does not match the next case is tested.
  • If the next case matches the expression, the code executes and exit out of the switch block.
  • If no cases match, the default code block is executed.

This is a simple example of the swtich statement evaluating an integer:



var i=2;

switch (i)
{
    case 1:
        console.log("value of i = 1");
        break;

    case 2:
        console.log("value of i = 2");
        break;

    case 3:
        console.log("value of i = 3");
        break;

    default:
        console.log("value of i is not equal to any given values");
        break;

This example demonstrates how to write the day of the week from the Date.getDate() method:


var my_day=new Date();

switch (my_day.getDay()) 
   {
    case 0:
        console.log("Today is Sunday");
        break;
    case 1:
        console.log("Today is Monday");
        break;

    case 2:
        console.log("Today is Tuesday");
        break;

    case 3:
        console.log("Today is Wednesday");
        break;

    case 4:
        console.log("Today is Thursday");
        break;

    case 5:
        console.log("Today is Friday");
        break;

    case 6:
        console.log("Today is Saturday");
        break;

    default:
        console.log("value of i is not equal to any given days");
        break;

}

You can also evaluate strings with the switch statement:



var text="Hello"; // Assigned a value to the variable text

switch (text) // Passing the variable to switch condition { case "Hello 1": console.log("Hello 1"); break;

case "Hello 2": console.log("Hello 2 "); break; case "Hello": console.log("Correct Text Hello "); break; default: console.log("This is default selection"); break; }

The Break Keyword

You may have already noticed the use of break for each statement. This causes the statement to 'break out' of the switch statement and continue to the next block of code. Without the break statement additional blocks may be executed if the evaluation matches the case value.

In other words when a match is found, and the job is done, if the break statement is encountered. Otherwise the switch statement will continue evaluating the expression.

You should be aware that the first match will be the statement that is executed. If you would like multiple matches to trigger code blocks then the break statement would stop that from happening.

It is not necessary to break the last case in a switch block. The block breaks (ends) there anyway.

JavaScript Switch Statement and Value Ranges

There have been several cases in my career when I needed to display different messages or maybe color indicators based on values. A good example is a dashboard to indicate the state of a system or key performance indicators.

Messages and visual queues are typically correlated to a value range, similar to kpis in school.

This example will return an object with a different text message and CSS class.



var kpi = 87;

switch (true) {
    // If score is 90 or greater
    case kpi >= 90:

return { "message": "Good", "cssClass": ".good-state" }; break; // If score is 80 or greater case kpi >= 80: return { "message": "OK", "cssClass": ".ok-state" }; break; // If score is 70 or greater case kpi >= 70: return { "message": "Poor", "cssClass": ".poor-state" }; break; // If score is 69 or less case kpi <= 69:="" return="" {="" "message":="" "failing",="" "cssclass":="" ".fail-state"="" };="" break;="" not="" available="" default:="" "na",="" ".na-state"="" }="" <="" code="">

The default state assumed the value was not available and returned a 'not available' object. You may render that with a grey color to indicate that visually. Of course it could also mean something is broken in the system and render a special warning, etc. It all depends on your application needs.

Ranges can be used because switch expressions can use any valid JavaScript expression syntax. Any expression you might use in an if statement can be used in a switch expression.

JavaScript Switch vs If Statement

Why would you use a switch statement instead of an if else?

Switch statements are cleaner syntax over a complex or stacked series of if else statements.

Use switch instead of if when:

  • You are comparing multiple possible conditions of an expression and the expression itself is non-trivial.
  • You have multiple values that may require the same code.
  • You have some values that will require essentially all of another value's execution, plus only a few statements.

Use if instead of switch when:

  • You want to test for the truthiness of an expression.
  • You only have a single affirmative test.
  • You need to evaluate different expressions for each branch

You could also mix switch and if else statements. If you have a second condition to evaluate, an if statement may be the right choice.

However, if the second condition is also complex you may want to refactor the code to execute into a separate method with it's own logic evaluation.

Extending the KPI example. Let's assume the default or 'not available' state has additional logic to determine a better message. For this example the real value being evalautated is an object with a kpi and source field.


var kpi = obj.kpi;

switch (true) {
    // If score is 90 or greater
    case kpi >= 90:

return { "message": "Good", "cssClass": ".good-state" }; break; // If score is 80 or greater case kpi >= 80: return { "message": "OK", "cssClass": ".ok-state" }; break; // If score is 70 or greater case kpi >= 70: return { "message": "Poor", "cssClass": ".poor-state" }; break; // If score is 69 or less case kpi <= 69:="" return="" {="" "message":="" "failing",="" "cssclass":="" ".fail-state"="" };="" break;="" not="" available="" default:="" if(obj.source="==" "google"){="" "google="" unavailable",="" ".google-na-state"="" else{="" "na",="" ".na-state"="" }="" <="" code="">

This is a simple change, but should serve to demonstrate how you can mix the two.

if, on the other hand the NA state triggered a more complex evalautation you may want to use a second swithc statement. To keep my code clean I would refactor that code to a seprate method:


    // Not available
    default:

return evaluateNAState(obj);

This keeps the code cleaner and makes it easier to unit test.

How you mix or use these examples is up to you and your discretion. I tend to opt for cleaner code with less duplicate code.

JavaScript Switch With Multiple Cases and Same Code

There are many cases where a range is not the right solution, but you need to apply the same execution to multuiple values. This is where the switch statement can be very handy.

Instead of creating a messy if statement with multiple expression evaluations you can 'stack' the cases.

This is a variation, all be it very simple, of the day of the week example. Here I am demonstrating how you might use the switch statement in a calendar application.


var my_day=new Date();

switch (my_day.getDay()) 
   {
    case 0:
        console.log("Sunday Brunch @ 11AM");
        break;
    case 1:
    case 2:
    case 3:
    case 4:
    case 5:
        console.log("In the Office by 8:30AM");

case 6: console.log("Morning Trail Run @ 7AM"); break; default: console.log("value of i is not equal to any given days"); break; }

Notice how the week day cases are stacked? I used the same code for those values, but applied different logic for the other days of the week.

How to Execute Multiple Cases

The break statement terminates the case statement execution. If a case does not include the break statement the next case is evaluated. If an additional match is found that statement is also executed.

I will use the date example to demonstrate how you might use this scenario:


var my_day=new Date();

switch (my_day.getDay()) 
   {
    case 0:
        console.log("Sunday Brunch @ 11AM");
        break;
    case 1:
    case 2:
    case 3:
    case 4:
    case 5:
        console.log("In the Office by 8:30AM");

case 3: console.log("It's hump day!!"); break; case 5: console.log("TGIF!!"); break; case 6: console.log("Morning Trail Run @ 7AM"); break; default: console.log("value of i is not equal to any given days"); break; }

In this example I extended the stacked example to add additional messages to be rendered on Wednesday and Friday. I removed the break statement from the weekday cases so the code would also evalauate for Wednesday and Friday.

The new cases included a break statement because they were specific days and there would be no need to evaluate further.

Matching Value Types

In the C# Switch article I demonstrated how you could match value types to trigger a statement. You can do the same in JavaScript.



var testObj = {};

switch (typeof testObj){

case "object": 
//do object processing

case "string": 
//do string processing

case "integer": 
//do integer processing
}

Summary

The switch statement is a fundamental coding pattern, supported by just about every language. Because JavaScript offers rich of the switch statement. Developers can utilize the switch statement to replace complex if else statements.

Share This Article With Your Friends!

Googles Ads Facebook Pixel Bing Pixel LinkedIn Pixel