<img alt="javascript switch" data- data-src="https://kirelos.com/wp-content/uploads/2023/09/echo/javascript-switch.jpg/w=800" data- decoding="async" height="420" src="data:image/svg xml,” width=”800″>

The JavaScript Switch statement is a conditional control flow statement. It is incredibly useful for creating conditional blocks with lots of clauses.

This article is a tutorial on the switch statement and how to use it. We will also compare it to other conditional constructs, if statements, and ternary operators so you may know when to use each.

What Is the Switch Statement in JavaScript?

The JavaScript Switch Statement is used to decide which branch of code to execute based on the value of an expression. It is one of the two conditional statements in JavaScript.

The first being the if-statement and the second being the ternary operator. It functions much like the two but has different nuances, making it ideal for some cases. In this article, we are going to explore all that.

How to Use JavaScript Switch Statement

In this portion of the article, I will explain the JavaScript Switch Statement and how to use it. I will use code examples, so you will need a JavaScript compiler to follow along. The easiest one to use is this online JavaScript Compiler. Alternatively, you can check our article on the best online JavaScript IDEs.

General Syntax

The general syntax for a switch statement is as follows:

switch() {
    case :
        
        break;
    case :
        
        break;
    default:
        
}

The switch keyword marks the beginning of a JavaScript switch block. Inside the parentheses, you put in any JavaScript expression. An expression is anything that evaluates to a value. For example, literals such as strings or numbers, variables, or function calls.

Next, we add the body of the switch statement between curly braces. The body is made up of several cases. Each case has a value and a group of statements. If the expression between the parentheses equals a case’s value, then that case’s statements are executed.

For each case, we can add the break keyword. Adding this word is entirely optional. If you add it, JavaScript breaks out of the switch block when it encounters it. If it is not present, JavaScript will continue to run all the cases after it. This is known as fall through. Unless you want to take advantage of fall through, it is recommended that you add the break keyword.

The last keyword to take note of is the default keyword. This case matches any value of the expression between the parentheses.

Examples

This section will demonstrate different examples of using the switch statement.

#1. With Fallthrough

Here is an example of using the switch statement without the break keyword. The purpose of this is to demonstrate fallthrough.

In this example, we are writing code to handle different HTTP status codes:

const statusCode = 

switch (statusCode) {
    case 200:
        console.log('OK');
    case 301:
        console.log('Redirect');
    case 403:
        console.log('Forbidden');
    case 404:
        console.log('Not Found');
    case 500:
        console.log('Internal Server Error')
}

In the code snippet above, we check if a value equals a particular status code, then print out a message describing the status code.

Observe what happens when you set the status code to 403.

<img alt="With Fallthrough" data- data-src="https://kirelos.com/wp-content/uploads/2023/09/echo/Screenshot-from-2023-09-26-13-37-22.png/w=800" data- decoding="async" src="data:image/svg xml,” width=”800″>

After matching the 403 cases, all the cases following it were also matched. This is called fallthrough. This is not ideal, as we often like to match one case. This weird quirk of JavaScript is the reason why it is necessary to add the break keyword.

#2. Without Fallthrough

To avoid fallthrough, we add the break keyword at the end of each case. The following example demonstrates what happens when you do.

const statusCode = 

switch (statusCode) {
    case 200:
        console.log('OK');
        break;
    case 301:
        console.log('Redirect');
        break;
    case 403:
        console.log('Forbidden');
        break;
    case 404:
        console.log('Not Found');
        break;
    case 500:
        console.log('Internal Server Error')
        break;
}

And when you run the code above with the status code 403, you get this.

<img alt="Without Fallthrough" data- data-src="https://kirelos.com/wp-content/uploads/2023/09/echo/Screenshot-from-2023-09-26-13-55-36.png/w=800" data- decoding="async" src="data:image/svg xml,” width=”800″>

As you can see, the code now matches just one case and avoids fallthrough.

#3. Useful Fallthrough

That said, it is important to note that fallthrough can be useful in some cases. Consider the following example where we want to check if a person is moving horizontally or vertically based on directional input.

const direction = ''

switch(direction) {
    case 'left':
    case 'right':
        console.log('horizontal movement');
        break;
    case 'up':
    case 'down':
        console.log('horizontal movement');
        break;
}

If you set the direction to left and run the code above, this is the result:

<img alt="Useful Fallthrough" data- data-src="https://kirelos.com/wp-content/uploads/2023/09/echo/Screenshot-from-2023-09-27-08-20-29.png/w=800" data- decoding="async" src="data:image/svg xml,” width=”800″>

And when you set the direction to right, you still get the same result:

<img alt="Useful Fallthrough -" data- data-src="https://kirelos.com/wp-content/uploads/2023/09/echo/Screenshot-from-2023-09-27-08-20-29-1.png/w=800" data- decoding="async" src="data:image/svg xml,” width=”800″>

This is because when the left case matches, it falls through to the right case and prints ‘horizontal movement’. But since there is a break keyword, it does not fall through to the up case. When the right case matches, it runs the statements in the right case and breaks.

Therefore, ‘horizontal movement’ is displayed when the direction is either left or right. Therefore, fallthrough allows you to create OR logic in your code.

#4. Matching Ranges

The JavaScript switch statement checks if the value of a case equals the value of the expression. If so, it executes the statements in that case. However, you may sometimes want to check if a value is in a given range. Matching ranges can be tricky, but the code snippet below demonstrates a workaround.

In the example below, we are implementing a program that, given a mark, prints out the grade. For example, if the mark is above 90, the program will print A . If it is above 80 but less than 90, it will print A, and so on.

To do this, I have put the expression true inside the parentheses. Then, the value of each case has been defined as a logical operation that will only be true if the mark is in the range for that case. For example, the last case mark >= 90 will only be true if the mark is greater than or equal to 90. Therefore, it will match the value of the expression since true equals true.

const mark = ;

switch (true) {
    case mark >= 50 && mark = 60 && mark = 70 && mark = 80 && mark = 90:
        console.log('A ')
        break;
    default:
        console.log('<50')
}

The output of the code above when the mark is set to 80 is:

<img alt="Matching Ranges" data- data-src="https://kirelos.com/wp-content/uploads/2023/09/echo/Screenshot-from-2023-09-26-13-10-16.png/w=800" data- decoding="async" src="data:image/svg xml,” width=”800″>

And when the mark is set to 95:

<img alt="Matching Ranges-" data- data-src="https://kirelos.com/wp-content/uploads/2023/09/echo/Screenshot-from-2023-09-26-13-12-04.png/w=800" data- decoding="async" src="data:image/svg xml,” width=”800″>

And when the mark is 45:

<img alt="Matching Ranges -" data- data-src="https://kirelos.com/wp-content/uploads/2023/09/echo/Screenshot-from-2023-09-26-13-13-23.png/w=800" data- decoding="async" src="data:image/svg xml,” width=”800″>

Lexical Scoping

The statements inside a case in a switch are not lexically scoped. This means variables defined in one case will be accessible in a different case. This is important to know as you write switch blocks where more than one case will be matched. Here’s an example to explain this better:

switch (true) {
    case true:
        let num = 10
    case true:
        console.log(num);
}

In the code snippet above, both cases match. In the first case, we define the num variable; in the second, we access its value. We won’t get any errors, as you can see from the screenshot below:

<img alt="Lexical Scoping" data- data-src="https://kirelos.com/wp-content/uploads/2023/09/echo/Screenshot-from-2023-09-26-15-13-58.png/w=800" data- decoding="async" src="data:image/svg xml,” width=”800″>

Difference Between a Switch Statement and Other Conditionals

A Switch statement is better suited to scenarios where you are testing for multiple conditions. An if-statement is suited to conditions where you are testing 2 or 3 conditions. A ternary operator is only good for conditions when you want to express a conditional as a one-liner.

For brevity, you should opt to write ternary operators first. If it is impossible to express the logic in a ternary operator, then you may use an if-statement. But if that is not possible, you opt for the switch statement.

Conclusion

This article covered the switch statement, how to use it, and its weird quirks. We also covered when to use it.

Next, you may want to polish up on JavaScript using these JavaScript cheat sheets.