Apart from the if family of conditional statements, JavaScript and many other programming languages, come equipped with another way to layout conditional code - the switch.

In this chapter, we shall discover the basic syntax of switch, how it can be used in practical scenarios and finally go over some cases where switch takes an upperhand over the usual if statement.

What is switch?

Often times you'll encounter cases where you need to test the same thing over and over again in a piece of code, to perform different actions on each outcome.

Following is an example of such a case:

var rating = 1;

if (rating === 1) console.log("Very Poor");
else if (rating === 2) console.log("Poor");
else if (rating === 3) console.log("Average");
else if (rating === 4) console.log("Good");
else if (rating === 5) console.log("Excellent");

There is a variable rating and then a whole list of if and else if statements to make different logs to the console based on the value of rating.

Notice the amount of repetition in this piece of code - we have to write rating === again and again in all statements in addition to writing else if a couple of times. For such a simple scenario, this code makes the situation look a lot more frustrating and uncouth, both to write and visually digest!

The solution to this mess is very easy - use switch instead.

Syntax of switch

The basic syntax of a switch statement is quite different from how an if statement is layed out. Nonetheless it is pretty elegant and sufficiently easy to remember.

Here's the general form of switch:

switch (expression) {
    case match1:
        // Code to execute if expression is equal to match1
        break;
    case match2:
        // Code to execute if expression is equal to match2
        break;
    default:
        // Code to execute when nothing is matched
}
Where:
  1. expression is the expression to match against. The expression's value is matched against the specified cases and when a match is found the underlying block of code is executed
  2. match1 is the first variable or literal to match against
  3. match2 is another variable or literal to match against

Now let's put this syntax into real action, by rewriting the rating example above using switch.

var rating = 1;

switch (rating) {
    case 1:
        console.log("Very Poor");
        break;
    case 2:
        console.log("Poor");
        break;
    case 3:
        console.log("Average");
        break;
    case 4:
        console.log("Good");
        break;
    case 5:
        console.log("Excellent");
        break;
}

Since the equality checks need to be run on rating, it goes inside the header of the switch statement. Then follows each case and its corresponding block of code together with the break keyword.

The way this code works is detailed as follows:

The JavaScript interpreter first evaluates the value of reading and then goes over each case separately, in the order written, running a strict equality === check between the case expression and reading.

Once it encounters a match, it transfers execution flow into the corresponding case block. For this example it means passing execution to line 5. Once all the code is executed, the interpreter finally encounters the break keyword and breaks execution out of the switch statement.

You might look back at the if version of this code and say that switch is useless and perhaps involves more repetitions than the easier if.

What you have to realise is that this is a very simple example - in much complex practical-level scenarios switch definitely brings elegance and ease with it, and removes the monotonous === operators from being used again and again.

What are these breaks?

For all the curious programmers out there who want to know the purpose of every statement they possibly could, this section discusses about the purpose of adding the break keyword inside switch's case blocks.

So what does break do?

By default i.e without the break keyword, once a case in a switch statement is matched, it's corresponding block is executed and even the ones that follow it, regardless of the case expression.

This means that the code below won't just log once but instead log twice; first for case 200 and then for case 300.

var status = 200;
switch (status) {
    case 200:
        console.log("First case done!");
    case 300:
        console.log("Second case done!");
}
First case done!
Second case done!

What is happening over here is that the interpreter first reads status and then matches it against the first case. Since a match is found, the underlying code in line 4 is executed.

After this, because there is no break inside the first case block, execution will be passed to the next case block regardless of the fact that it doesn't match the current value of status. This will get line 6 executed, and as a whole two logs to be made to the console instead of just one.

The break keyword simply prevents this normal execution flow. Once encountered, it breaks the flow out the switch statement, thus preventing any other cases from being executed.
You'll encounter break once again in the JavaScript Loops unit where it serves exactly the same purpose it does over here i.e break out of the current execution flow.

So although not a necessity, you'll see break in almost all switch statements out there; because in most cases there is no need to carry on execution further once a case is met.

Things to note

There may be things in the switch statement that you are unaware of like the break keyword. The following points clarify such things.
  1. For a case to match an expression both should have the same data type or else the case would fail and pass the flow to the next case (if any).
    var num = 1; // type number
    switch(num) {
        // case of type string
        case "1":
            alert("String matches string");
            break;
    
        // case of type number
        case 1:
            alert("Number matches number");
            break;
    }
    The output in this case is Number matches number.

    You could also have the following doing essentially the same thing as in the previous example.
    var num = 1; // type number
    switch(String(num)) {
        // case of type string
        case "1":
            alert("String matches string");
            break;
    
        // case of type number
        case 1:
            alert("Number matches number");
            break;
    }

  2. The break keyword in all these examples tells the interpreter to break out of the switch statement as soon as it's reached. So when the break keyword is encountered the rest of the code in the switch block is skipped.
  3. The default keyword specifies the default code to execute if none of the cases match the expression.

When to use switch

Use the switch when statement:
  1. When you literally have to select from a given list of cases (options) and execute code accordingly.
  2. When you know the possible cases that an expression, to test for, can have
  3. When the condition testing doesn't requires nesting and more control over the code.

In conclusion

The switch statement may be occasionally used but when used saves a lot of time and lines of code that would've been wasted if replaced by the if statement.

The next chapter explores one more avenue of conditional programming, that is particularly useful for condition-based assignment in one line, and then we are done with another unit, infact another major unit.