javascript - javascript switch - javascript switch statement - switch case

Executing Instructions Based on Fixed Values with Javascript Switch Statements

Javascript switch statements are a form of control statement similar to if-else statements. They determine whether an expression evaluates to one of many possible values, then execute instructions based on that value.

Overview of Javascript Switch Statements

The switch statement uses reserved words to identify each of its parts:

  • switch — the switch statement
  • case — identifies a valid value for the expression the statement evaluates
  • default — special case used when an expression evaluates to an invalid value
  • break — terminates execution of instructions within a case
switch (expression) {
    case 1:
        ... instructions …
        break;
    case 2:
        ... instructions …
        break;
    default:
        ... instructions …
        break;
}

Unlike an if else statement, a switch statement does not stop evaluating its values once it finds a match for the expression. Unless you force execution to stop with the reserved word “break,” a switch statement will continue evaluating cases after the matched case.

In the code below, if the expression evaluated to 1, the instructions under case 1, case 2, and the default case would all be executed.

switch (expression) {
    case 1:
        ... instructions ...
    case 2:
        ... instructions ...
    default:
        ... instructions ...
}

This behavior is called fall-through, and is the source of many unintentional errors in switch statements. Fall-through can be useful, however, if you have multiple cases within a switch statement that should execute the same code:

switch (expression) {
    case 1:
    case 3:
        ... instructions ...
        break;
    case 2:
        ... instructions ...
        break;
    default:
        ... instructions ...
        break;
}

Switch statements are always evaluated from top to bottom. The order of cases does not matter as long as you always have the reserved word “break” at the end of all cases that shouldn’t have fall-through.

The result of the expression in the switch statement must have the same type and value as a case in order to execute that case’s instructions. This is called strict comparison.

In the following example, the expression would match the default case, since the string “1” is not the same type and value as the number 1 required to match a case. The case requires a number, not a string, so the comparison for the case fails.

let x = “1”;
switch (x) {
    case 1:
        ... instructions ...
        break;
    default:
        ... instructions ...
        break;
}

When to Use Javascript Switch Statements

Javascript switch statements describe actions that should take place if an expression evaluates to a certain value, so they shouldn’t be used for major logical flows in a program. If else statements are better suited for defining logic.

A switch statement creates a table behind the scenes which doesn’t need to be re-evaluated every time the program encounters it, making it much faster than the equivalent if-else statement. Switch statements are especially useful, then, for handling fixed values when there are many different possible options.

A dynamically typed language — like Javascript — may not always reap the same speed benefits from this approach as a more strongly typed language like C++ would. Switch statements still require less computation than if-else statements, though, which results in lower execution times, a key factor in creating unobtrusive Javascript.

You may also be able to translate a long chain of if else statements into a single switch statement. When this is possible, readability and speed both increase, but all conditions within the if else statements must translate to fixed values.

//
// If else statement chain
//
let x = resultFromAFunction();
if (x == 1) {
    ... instructions ...
} else if (x == 2) {
    ... instructions ...
} else if (x == 3) {
    ... instructions ...
} else if (x == 4) {
    ... instructions ...
} else if (x == 5) {
    ... instructions ...
} else {
    ... instructions ...
}

//
// Switch statement
//
switch (resultFromAFunction()) {
    case 1:
        ... instructions ...
        break;
    case 2:
        ... instructions ...
        break;
    case 3:
        ... instructions ...
        break;
    case 4:
        ... instructions ...
        break;
    case 5:
        ... instructions ...
        break;
    default:
        ... instructions ...
        break;
}

Best Practices for Javascript Switch Statements

Keep the Code Simple

When writing instructions for a case inside a switch statement, you can create any kind of code you wish. Adding variable declarations and other control structures can make a switch statement complicated quickly:

switch (resultFromAFunction()) {
    case 1:
        if (doThis) {
            ... instructions ...
        }
        ... instructions ...
        break;
    case 2:
        ... instructions ...
        while (somethingElse) {
            ... instructions ...
        }
        break;
    default:
        ... instructions ...
        break;
}

Try to make the instructions for every case as small as possible so they can be easily understood at a glance. Ideally, stick to simple variable assignments. If you find your cases are getting complicated, an if else statement might better suit your needs.

Be Consistent in Case Handling

A switch statement lets you put the default case wherever you want in the list of cases, as long as you use the reserved word “break” at the end of the case. For readability and maintenance, most programmers expect to see a “default” at the very beginning or very end of the case list.

Choose one of these places and stick to it throughout your program — neither one gives an advantage over the other, so choose whichever one is easier to remember. It’s much easier to find a default case in a large switch statement if you consistently know where to look.

//
// Default at beginning of switch
//
switch (expression) {
    default:
        ... instructions ...
        break;
    case 1:
        ... instructions ...
        break;
    case 2:
        ... instructions ...
        break;
}

//
// Default at end of switch
//
switch (expression) {
    case 1:
        ... instructions ...
        break;
    case 2:
        ... instructions ...
        break;
    default:
        ... instructions ...
        break;
}

Use Distinct Cases Whenever Possible

Since a switch statement uses strict comparisons, it’s not going to be confused if you have two cases that have similar values of different types. People trying to maintain your code might be confused, as in this example where the first case is the number 1 and the second case is the string “1.”:

switch (expression) {
    case 1:
        ... instructions ...
        break;
    case “1”:
        ... instructions ...
        break;
    default:
        ... instructions ...
        break;
}

At first glance when maintaining the code, the number 1 and the string “1” look very similar, and it might not be clear why those two cases need to be different. When you have similar cases like this, it’s often an indication that you can simplify your code by making sure all case values are the same type before comparing them.

If you can’t simplify your code and absolutely need similar cases, make sure that you add comments to the switch statement clarifying why the cases are similar and what they each do differently.

Conclusion

Although switch statements and if-else statements both execute code based on the results of a calculation, the two statement types have different strengths and are not interchangeable. Switch statements are not suitable for creating complex logical flows as if else statements are.

Enroll in our Intro to Programming Nanodegree program today to learn more about Javascript switch statements and other programming concepts.

Start Learning

Jessica Reuter Castrogiovanni
Jessica Reuter Castrogiovanni