JavaScript Switch

The switch statement evaluates an expression, matching the expression's value to a case clause, and executes statements associated with that case.so When the switch executes, it finds the first matching case statement and then executes each line of code after the switch until it hits either a break statement or the end of the switch (or a return statement to leave the entire containing function).

The JavaScript switch statement is used to execute one code from multiple expressions. It is just like else if statement. So A switch statement first evaluates its expression. It then looks for the first case clause whose expression evaluates to the same value as the result of the input expression and transfers control to that clause, executing the associated statements. If no matching case clause is found, the program looks for the optional default clause, and if found, transfers control to that clause.

The signature of JavaScript switch statement is given below.

switch (expression)
{
  case value1:
    // executed when result matches value1
    [break;]
  case value2:
    //Executed when result matches value2
    [break;]
  ...
  case valueN:
    // executed when result matches value…n
    [break;]
  [default:
    // executed when none of the values match
    [break;]]
}

example of switch statement.
<script>
    var Cource = 'C';
    var result;
    switch (Cource) {
        case 'A':
            result = “MCA";
            break;
        case 'B':
            result = "BCA";
            break;
        case 'C':
            result = “BBA";
            break;
        default:
            result = "NO COURCE";
    }
    document.write(result);

</script>

Output
BBA


Example -2

<script>
    var Input = 2;
    var result;
    switch (Input)
    {
        case 1:
            result = "Case 1 code execute ";
            break;
        case 2:
            result = "Case 2 code execute ";
            break;
        case 3:
            result = "Case 3 code execute ";
            break;
        default:
            result = "default code execute ";
    }
    document.write(result);

</script>



OUTPUT

Case 2 code execute