How to use switch statement in JavaScript?

We are learning about decision making in various languages throughout our entire life. In this post, we will see how to use switch statement in JavaScript. You might have seen other decision-making statements like if-else. But the most convenient way is the switch statement as compared to if-else statements.

Consider a situation where we have to test a variable for a hundred different values and based on the conditions we want to perform some task. If-else statement would be less efficient over it and also it will look messy.

The switch is a multiway branch statement. It provides a better way to execute the different parts of code based on the value of the expression.

Syntax:

switch (expression){
    case value1:
        statement1;
        break;
    case value2:
        statement2;
        break;
    .
    .
    case valueN:
        statementN;
        break;
    default:
        statement Default;
}

If you see the above syntax it accepts an expression which is a simple variable holding the numeric or string value. Duplicate values are not allowed in the switch statement and default statement is always optional. So you can omit the default statement if you don’t want it. The default case is executed only if the expression passed to the switch statement doesn’t match the value of any case. You might have noticed the break statement in the syntax above. The break statement is used to terminate the statement sequence, it is optional and if you omit the break statement the execution will continue to the next case.

Example:

var number = 3;

switch (number){
    case 0:
        document.write("Number is 0.");
        break;
    case 1:
        document.write("Number is 1.");
        break;
    case 2:
        document.write("Number is 2.");
        break;
    default:
        document.write("Number is 3.");
}

Output:
Number is 3.

In the above example, you see how easy is the implementation of the switch statement in JavaScript. So next time you can use it in your coding practice to write the good looking code.

Leave a Reply