Google News
logo
Javascript Switch Statement
JavaScript switch statement evaluates a switch condition, base on switch condition value matched case will run until break or end of case statement.
Syntax :
switch (expression)
{
   case condition 1: statement(s)
   break;
   
   case condition 2: statement(s)
   break;
   ...
   
   case condition n: statement(s)
   break;
   
   default: statement(s)
}
Javascript Switch statement (With break keyword)
break keyword is optional for end of the case statement execute.
Example :
<html>
<head>
<title>JavaScript Switch Case</title>
</head>
<body>
<pre> 
<script type="text/javascript">
var weekname = "saturday";
switch (weekname) {
    case "monday":
        document.writeln("Monday first day of the week..");
        break;
    case "tuesday":
        document.writeln("Tuesday second day of the week..");
        break;
    case "wednesday":
        document.writeln("Wednesday third day of the week..");
        break;
    case "thursday":
        document.writeln("Thursday fourth day of the week..");
        break;
    case "friday":
        document.writeln("Friday Fifth day of the week.");
        break;
    case "saturday":
        document.writeln("Saturday Sixth day of the week and week end.");
        break;
    case "sunday":
        document.writeln("Sunday Seventh day of the week and week end.");
        break;
    default:
        document.writeln("No any case found.");
}
</script>
</pre>
</body>
</html>   
Output :

Saturday Sixth day of the week and week end.

Javascript Switch statement (without break)
Without break; keyword matching case execute. Not only matching case but after all cases and default cases are execute.
Example :
<html>
<head>
<title>JavaScript Switch statement (without break keyword)</title>
</head>
<body>
<pre> 
<script type="text/javascript">

var weekname = "friday";
switch (weekname) {
    case "monday":
        document.writeln("Monday working day.");
    case "tuesday":
        document.writeln("Tuesday working day.");
    case "wednesday":
        document.writeln("Wednesday government holiday.");
    case "thursday":
        document.writeln("Thursday working day.");
    case "friday":
        document.writeln("Friday is a last working day of the week.");
    case "saturday":
        document.writeln("Saturday week end.");
    case "sunday":
        document.writeln("Sunday week end.");
    default:
        document.writeln("No any case found.");
}

</script>
</pre>
</body>
</html> 
Output :

Friday is a last working day of the week.
Saturday week end.
Sunday week end.
No any case found.