Switch Statement
Switch Statement
The Switch Statement is mainly used to perform different actions based on different conditions. It can eliminate the use of multiple if else if statements.
The switch condition is executed once if the value of the desired condition is compared with the values of each switch cases. If there is a match, then the desired block of code gets executed.
If not, then the default block of code gets executed as there is no match found.
The Break keyword is used to break out a switch block of code. It will stop the execution of further cases when the desired matching case execute.
Syntax
Switch (condition)
{
Case 1:
block of code
break;
Case 2:
block of code
break;
default:
block of code
}
Code:
<html>
<body>
<h2>The Switch Statement</h2>
<script>
var a = 2;
switch(a)
{
case 1:
document.write("Today is Monday");
break;
case 2:
document.write("Today is Tuesday");
break;
case 3:
document.write("Today is Wednesday");
break;
default:
document.write("No Case Found");
}
</script>
</body>
</html>
As per the above code, switch statements include multiple cases where each case represents a value, further when the execution proceeds to different cases then a new set of code gets executed and if the no match is found then the program executes the default case.
Here, in this code, the value of “a” is 2. So, the case 2 get executed.
Output: