How to use switch statement in JavaScript?

We are learning about the decision making in various language through out 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 switch statement as compared to if-else statements.

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

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


If you see the above syntax switch case statement accepts an expression which is simple variable holding the numeric or string value. Duplicate values are not allowed in switch statement and default statement is always optional. So you can omit the default statement if you don’t want it. Default case is executed only if the expression passed to switch statement doesn’t matches to the value of any case. You might have noticed the break statement in the syntax above. 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.


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

Your email address will not be published. Required fields are marked *