Making Decisions Using Switch Statement in Javascript featured image

Making Decisions Using Switch Statement in Javascript

Introduction

Conditional statements are one of the most important control flows in any programming language. We use them to dictate the behavior of execution upon some condition. In Javascript, conditional blocks can be built using if, else if, else, and switch statements.

The switch statement makes the control flow easy to read by making the decision against some possible outcomes to the expression. Depending on the matching use case, one or more blocks of code can be executed. The switch control is similar to the else if statement. However, switch is more readable syntax wise. It is also ideal for the scenarios with multiple possible outcomes.

In this tutorial, we will focus on the switch statement in Javascript and implement it to build complex control structures. We will also learn how to use the break , case, and default statements within the switch block to direct the flow of control.

Using the Switch Statement

The switch statement works by comparing the value of a variable against possible expressions. Then, it executes the block of code matching the outcome. The syntax of the switch  statement is no different from the if statement. In short, the syntax of the switch statement is written as:

Below is an example of the switch statement. It has two cases or two possible outcomes along with a fallback option specified by the default keyword. This fallback option is executed when the execution concludes or when no matching case is found:

The above code is executed as follows:

  1. First, the expression is evaluated.

  2. Next, the result of the expression is matched against the case x. If the value matches, the code block under the case x is executed.

  3. If the expression does not match against the case x, then the case y is matched. If the match is found, then the case y code is executed.

  4. Finally, if neither case x nor case y is matched, then the default code is executed and the control moves out of the switch block.

Working Example

To understand the switch statement, let’s take a look at a working example. We will be extracting the day of the week value for the current date, by using the getDay() method of the Javascript’s Date object. This value is a number, for Sunday all the way up to 6 which is for Saturday. We will evaluate it against the values to determine which day of the week it is:

Next, we will send this value to the switch statement. The switch statement will run from top to bottom to match it against cases to determine which day of the week it is. Once the case is found, the break command will stop the switch block from continuing to evaluate statements:

Depending on the value returned from the getDate() method, it will be tested against the cases one at a time, starting from the top. The output will be different depending on the day you have run the code. The default code block is placed so that if no case is matched, we can handle this scenario. However, here in this code, default will never be called since there are only a finite number of days of the week.

The break statement makes sure that once the case has been matched, no further cases are matched and the control comes out of the switch statement. This makes the program more efficient and faster.

Testing Against Ranges in Switch

Until now, we have been looking at very simple use cases. But there can be times when it is needed to test against a range of values as opposed to a single value. We can do this by setting our expression to true and doing an operation within each case statement.

Let’s demonstrate this use case with the help of an example. We will take a number and then, convert it into grade using the below categorization:

  • Grade of 90 and above is an A

  • Grade of 80 to 89 is a B

  • Grade of 70 to 79 is a C

  • Grade of 60 to 69 is a D

  • Grade of 59 or below is an F

We will write these statements as switch statements. Below is the code for this:

Unlike the above code examples, here we have set the expression in the parenthesis as true. Hence, whichever case statement matches the true value, it will be executed. Just like the else if statement, the first statement which matches the specified value will be executed. Here the output will be B, despite the fact that even C and D are also matching the expression.

Multiple Cases

If you want to have more than one case with the same code block, it is also possible. This is analogous to the or condition in the if statement. In such scenarios, we can specify more than one case for each block of code.

To illustrate this concept, we will provide an example with the months of the year. We will categorize these months into seasons of a year. First, we will use the new Date() method to find a number corresponding to the current month, and apply that to the month variable. The Date().getMonth() method returns a number from 0  to 11, with 0 being January and 11 attached to December.

We will categorize using the below specification:

  • Winter: January, February, and March

  • Spring: April, May, and June

  • Summer: July, August, and September

  • Autumn: October, November, and December

Here is how the code will look like:

When the above code is executed, depending upon the month, the name of the season will be pointed out on the console.

Conclusion

In this tutorial, we demonstrated how to use the switch statement in Javascript applications. We also applied the switch statement to a range and multiple cases along with the default keyword. If you want to learn more about Javascript, you can check out the following tutorials:

Happy Computing!