JavaScript Switch Statement

A switch statement could be used in many ways while java scripting. It can perform various actions based on different conditions. It can execute a code with different expressions. It works more or less same way like an if-else statement but it is more convenient to use compared to it. However, still some programmers find it is very hard to use and it is not used quite often in javascript.

Syntax of Switch Statement

Here is the default simple syntax of a JavaScript.

	
switch(expression) {     //this is the expression which is to be checked
    case n:
        code block
        break;
    case n:
        code block
        break;
    default:
        default code block // this is the value of the code which is to be executed if no match found
}

Example

	
<script>
switch (new Date().getDay()) {
    case 0:
        day = "Sunday";
        break;
    case 1:
        day = "Monday";
        break;
    case 2:
        day = "Tuesday";
        break;
    case 3:
        day = "Wednesday";
        break;
    case 4:
        day = "Thursday";
        break;
    case 5:
        day = "Friday";
        break;
    case 6:
        day = "Saturday";
}
</script>
	

How Switch Statement works

It can be used to check one type of expression or condition. The values for each case are compared based on the output of that expression. If match is found, then that particular line of code is executed based on the value and expression tested. Only the associated block of code is executed. There could be single or even multiple expressions tested in JavaScript switch statement and can be used with characters, numbers etc. One can use different type of expressions or cases which need to be tested and based on that code could be executed. It is very useful when there are various possibilities in the code.

Use of Break keyword in Switch

In the above example, you could see break statement is used. It is a useful way to terminate the switch statement when the line of codes or required expression is executed. If break statement is not used, then it could cause an endless loop. Every case under switch statement is terminated with break statement.



Next ConceptJavaScript Loop