JavaScript Switch Statement

In this article, we will explore the JavaScript Switch Statement, utilizing various examples to illustrate its functionality.

What is a Switch Case in JavaScript?

In JavaScript, the switch case construct serves as a conditional statement that allows for the execution of various blocks of code depending on the result of an expression.

A switch case statement is employed to execute various operations depending on the conditions defined within the program or specified by the user.

To put it differently, a switch statement assesses the condition to align it with a set of specified cases. When the condition finds a match, the corresponding statement is executed. Conversely, if the condition does not correspond to any of the cases, the default case will be executed instead.

In JavaScript, a switch case statement serves as an alternative method to the traditional if-else constructs.

The switch statement in JavaScript serves the purpose of executing a specific block of code depending on various expressions. It offers a more convenient alternative to using if-else chains, as it can operate with a range of data types, including numbers, characters, and more.

The illustration provided beneath depicts the flow of control within the JavaScript switch statement:

Syntax

Let’s examine the syntax of the Switch case statement in JavaScript:

Example

switch (expression) {  

  case value1:  

    // Code to be executed  

    break;  

  case value2:  

    // Code to be executed  

    break;  

  default:  

    // Code to be executed if no case matches  

}

Explanation:

  • expression: It is a value that is evaluated once. It can be a variable or a direct value.
  • case value1: The JavaScript will compare the case value1 to the value of the expression. If they are equal, then the code of case value1 will be executed otherwise, it will jump to the next case.
  • break: The execution of the current case is stopped by the break statement and exits the switch block.
  • default: It is optional. This block runs when none of the given case values match the expression.
  • Break Statement:

In JavaScript, the keyword break is utilized within the switch-case construct. This keyword signifies the conclusion of a specific case within the switch statement. When using a switch statement, if a break statement is not included, the execution will proceed into the subsequent case without interruption.

Default Statement

In JavaScript, the keyword default is employed within a switch statement to designate the default expression. When none of the cases correspond with the expression evaluated in the switch-case statement, the default code block is executed. This feature is essential for avoiding unforeseen behaviors. The placement of the default statement within a switch statement does not impact its functionality. The block of code within the default statement is executed only when none of the preceding cases match; it will consistently run if no case aligns. It is important to note that declaring a default statement is not mandatory; it can be excluded if it is deemed unnecessary.

Example 1: Simple Program with a Switch Case Statement

Consider a straightforward program that utilizes a switch case statement in JavaScript:

Example

Example

const expression = 'apple';  

switch (expression){  

    case 'orange':  

        console.log('I prefer orange.');  

        break;  

    case 'watermelon':  

        console.log('I prefer watermelon too!');  

        break;  

    case 'apple':  

        console.log('An apple a day keeps the doctor away.');  

      break;  

    default:  

        console.log(`Sorry, we are out of ${expression}`);  

}

Output:

Output

An apple a day keeps the doctor away.

Explanation:

In the preceding code, a variable titled expression was declared using the const keyword. We assigned it the string value "apple." At this point, the switch(expression) statement is executed by JavaScript, which subsequently compares the value of expression against each defined case. For the case "orange," if the expression matches "orange," it will output "I prefer orange." However, since "apple" does not match "orange," this case is bypassed. The next comparison is made with the case "watermelon," but once again, "apple" does not equal "watermelon," leading to this case also being skipped. The comparison then shifts to the case "apple," where "apple" indeed matches the value of the expression. Consequently, it outputs "An apple a day keeps the doctor away." Following this output, the break statement concludes the execution of the switch block and exits it.

Example 2: Switch Case Statement without Break Statement.

Let’s consider an example that demonstrates the functionality of loops in JavaScript without utilizing the break statement.

In this instance, we will employ a for loop to iterate through an array of numbers and print each number to the console. By avoiding the use of break, we ensure that the loop continues executing until it has processed every element of the array.

Here’s how it can be accomplished:

Example

const numbers = [1, 2, 3, 4, 5];

for (let i = 0; i < numbers.length; i++) {
    console.log(numbers[i]);
}

In this example:

  • We declare an array named numbers containing five integer values.
  • The for loop is initialized with a variable i set to 0.
  • The loop will run as long as i is less than the total number of elements in the numbers array.
  • Within each iteration, the current element is accessed using numbers[i] and printed to the console.

As a result, the output will be:

Example

1
2
3
4
5

This approach highlights how we can effectively traverse an array and output its contents without the need for prematurely exiting the loop using a break statement.

Example

Example

// without the use of a break in JavaScript  

const expression = 'apples';  

switch (expression){  

    case 'oranges':  

        console.log('I prefer orange.');  

      

    case 'watermelons':  

        console.log('I prefer watermelon too!');  

         

    case 'apples':  

        console.log('An apple a day keeps the doctor away.');  

       

   default:  

        console.log(`Sorry, we are out of ${expression}.`);  

}

Output:

Output

An apple a day keeps the doctor away. 

Sorry, we are out of apples.

Explanation:

In the preceding code, we established a variable called expression using the const keyword. We assigned it the string value "apples". At this point, JavaScript evaluates switch(expression), comparing the value of expression against each case. Initially, it assesses the case "oranges" alongside the value of the expression; however, since "oranges" does not match "apples", this case is bypassed. Next, it evaluates the case of "watermelons" against the value of the expression, which also does not equate to "apples." Following that, it examines the case "apples" against the value of the expression. The case "apples" indeed matches "apples." Consequently, it outputs "An apple a day keeps the doctor away." Subsequently, it displays "Sorry, we are out of apple." The default code was executed as well, due to the absence of a break statement, which allowed the execution to flow into the default block.

Example 3: Defining a Default Keyword in the Middle

Consider a scenario where we position the default keyword in the center of our code.

Example

Example

const expression = 'apple';  

switch (expression){  

    case 'orange':  

        console.log('I prefer orange.');  

        break;  

    case 'watermelon':  

        console.log('I prefer watermelon too!');  

        break;  

    default:  

        console.log(`Unfortunately, we are out of ${expression} at the moment`);  

       break;

    case 'apple':  

        console.log('An apple a day keeps the doctor away.');  



}

Output:

Output

An apple a day keeps the doctor away.

Explanation:

In the code presented above, we have defined a variable called expression using the const keyword. We have assigned it the string value "apple". In this scenario, JavaScript evaluates switch(expression), checking the value of expression against each case. Initially, it checks the case "orange" against the expression's value; however, since "orange" does not match "apple", this case is bypassed. Next, the comparison of the case "watermelon" with the expression's value occurs. Again, "watermelon" does not equal "apple". Finally, the case "apple" is evaluated against the expression's value, and here, "apple" matches "apple". Additionally, we have positioned a default statement in the middle of our cases. This arrangement is acceptable, as the sequence of cases does not influence the execution; the default statement will only be executed if none of the preceding cases are satisfied.

Example 4: Common Code Blocks

There are instances when it is necessary to execute the same block of code across various case labels within a switch statement. Rather than repeating the same code for each case, we can consolidate it. Let’s illustrate this concept through an example.

Example

Example

let studentGrade = 'A'; 

let result;



switch (studentGrade) {

    case 'A':

    case 'B':

    case 'C':

        result = "Grade is very good."; 

        break;

    case 'D':

        result = "Grade is poor.";

        break;

    default:

        result = "No grade is achieved.";  

}



console.log(result);

Output:

Output

Grade is very good.

Explanation:

In the preceding example, we declared a variable called studentGrade utilizing the let keyword and assigned it a string value. In this context, we have combined case 'A', case 'B', and case 'C', all of which convey the identical message: "Grade is very good." Additionally, we established a default case to manage any invalid inputs. If none of the specified cases align, it will return "No grade is achieved." For instance, if studentGrade equals 'A', the output will be "Grade is good."

How do switch statements work?

Evaluation

In JavaScript, within a switch case statement, the expression is assessed a single time.

Comparison

In JavaScript, when employing the switch statement, the expression's value is evaluated against each case using strict equality (===).

Execution

In JavaScript, when a matching expression is identified within a switch case statement, the associated code block that follows the matched expression will be executed. If no expression matches, the flow of execution will proceed to the default case; otherwise, it will continue with the subsequent statement that appears after the switch block.

Break Statement

Upon the completion of the code segment within a program, the break statement serves to conclude the switch statement, thereby averting the execution from progressing into the subsequent cases. This behavior is commonly referred to as fall-through.

Default Case

In JavaScript, the default case is not mandatory, allowing developers the choice of whether to implement it. When there is no corresponding match found within the code, the instructions contained in the default case block will be executed.

Difference between if-else and switch statements

Syntax

Switch statement: In JavaScript, the switch construct is initiated with the switch keyword, succeeded by parentheses that contain an expression. Following this, a sequence of case statements is presented.

If-else construct: This structure employs the if keyword, which is succeeded by a condition encapsulated in parentheses, along with an optional else statement.

Purpose

Switch Statement: In JavaScript, the switch statement evaluates a singular expression against various cases and executes the corresponding block of code that aligns with the matched case.

If-else statement: Within JavaScript, an if statement evaluates a specific condition and runs distinct code segments depending on the truth value of that condition, either true or false.

Cases

Switch statement: In JavaScript, a switch statement is capable of containing several cases, with each case potentially having a distinct value that corresponds to the evaluated expression.

If-else construct: Within the if-else construct, there exist solely two potential code segments; one is executed when the condition evaluates to true, and the other is activated when the condition is false.

Default

Switch statement: In JavaScript, it is possible to incorporate a default case that will be executed when none of the case statements correspond to the provided expression within the program.

If-else statement: In JavaScript, the else clause can be incorporated to perform a specific action when the condition evaluates to false.

Efficiency

Switch Statement: This construct can provide greater efficiency when there are numerous cases to evaluate in comparison to the if-else construct.

Conditional statements (if-else): They may exhibit lower efficiency in comparison to the switch statement, particularly when handling numerous cases or conditions.

Readability

Switch statement: In JavaScript, utilizing the switch statement can enhance readability when dealing with numerous conditions, as opposed to using an if-else statement.

If-else statement: In JavaScript, the if-else construct can offer greater flexibility and strength when compared to the switch statement, especially when addressing intricate conditions that need to be evaluated.

Ultimately, both the switch statement and the if-else statement possess their own strengths and weaknesses. The choice between the two often relies on the particular needs of the program or the preferences of the developer.

Conclusion

The Switch statement in JavaScript serves as a conditional construct designed to manage multiple conditional statements, relying on the outcome of a specific expression. This topic is fundamental in JavaScript programming. In this article, we have explored the JavaScript switch statement through a variety of examples, discussed the significance of the break statement within the switch statement, and addressed frequently asked questions. It is crucial for developers to grasp this concept as it plays a vital role in decision-making processes in JavaScript.

FAQs:

Below are some commonly posed inquiries:

  1. What are the drawbacks associated with a switch-case statement?

Some of the disadvantages of switch statements are given below:

  • We cannot utilize the float constant in the switch as well as in the case .
  • It does not allow us to use variable expressions in a case.
  • We cannot utilize the same constant in two different cases.
  • The relational expression cannot be utilized in a case.
  1. In JavaScript, can we nest switch statements?

While it is possible to implement a nested switch statement, such an approach can rapidly become complex and hard to interpret, making it less than ideal. A better practice involves leveraging functions in conjunction with the nested switch statement to enhance code readability. Additionally, a recursive function can also be employed to streamline the process.

  1. Is it essential for switch statements to always include a default case?

No, the switch statement isn't required to include a default case. A developer implements a default case only when there is an action to perform, such as handling an error scenario or establishing a standard behavior.

  1. Is it necessary to employ a break statement within a switch case?

It is not mandatory to use the break statement within a Switch Statement. However, omitting the break statement can result in an unintended behavior referred to as fall-through.

  1. Is switch-case more efficient than if?

Indeed, the switch statement is generally more efficient than an if statement. In the case of a switch statement, the compiler constructs a jump table. When the switch is invoked, it does not evaluate each case sequentially to find a match; rather, it directly identifies the appropriate case to execute.

Input Required

This code uses input(). Please provide values below: