Switch Case Statement
How to use switch case statements in javascript?
What are the options when a condition may have numerous result?
Explanation
Switch case is used to when a condition may have multiple results and a different set of operation is done based on each result..
Syntax:Switch(condition)
{
case result1:
// Operation for result1
case result2:
// Operation for result2
.
.
.
default :
// If result belongs to none of the case specified
}Example:
<script language="javascript">
for(var i=1; i<5; i++)
{
switch(i)
{
case 1:
document.write("message for case 1 <br>");
break;
case 2:
document.write("message for case 2 <br>");
break;
case 3:
document.write("message for case 3 <br>");
break;
default:
document.write("message for case default<br>");
break;
}
}
</script>
Result:
In the above example we have used
for loop to explain switch case statement. Here each time the value of i is different and increases as 1, 2, 3, 4. There are three case defined for 1, 2, 3. When value is 4, default is executed.