Learn What Is JavaScript Switch Statement

Posted by TotalDC

You have learned about decision-making in JavaScript using if-else statements in our previous article on if-else statements in JavaScript. You have seen in previous articles that you can use the if-else statements to perform actions based on some particular condition. That is if a condition is true then perform some task or else if the condition is false then do some other task. Now let’s learn about the JavaScript switch statement.

Learn What JavaScript Switch Statement Is And How To Use JavaScript Switch Statement

The JavaScript switch statement is also used for decision-making purposes. In some cases using the switch case statement is seen to be more convenient than if-else statements. Consider a situation when you want to test a variable for maybe a hundred different values and based on the test you want to execute a particular task. Using if-else statements for this purpose will be less efficient than switch case statements and also it will make the code look messy.

The switch case statement is a multiway branch statement. It provides an easy way to dispatch execution to different parts of code based on the value of the expression.

Syntax:

switch (expression)
{
    case value1:
        statement1;
        break;
    case value2:
        statement2;
        break;
    case value3:
        statement3;
        break;
.
.
.
    default:
        statementDefault;
}

Explanation:

  • expression can be of type numbers or strings.
  • Dulplicate case values are not allowed.
  • The default statement is optional. If the expression passed to switch does not match with value in any case then the statement under default will be executed.
  • The break statement is used inside the switch to terminate a statement sequence.
  • The break statement is optional. If omitted, execution will continue into the next case.

Example:

<script type = "text/javascript">

    // JavaScript program to illustrate switch-case
    let i = 9; 

    switch (i)  
    { 
       case 0: 
           console.log("i is zero."); 
           break; 
       case 1: 
           console.log("i is one."); 
           break; 
       case 2: 
           console.log("i is two."); 
           break; 
       default: 
           console.log("i is greater than 2."); 
    }

</script>

The result of this code would be “i is greater than 2.”.