Home >>Javascript Tutorial >JavaScript Switch
In order to execute one code from multiple expressions, JavaScript Switch is used. It is known to be very similar to the if-else statement and due to the permitted use of numbers and characters it is more convenient than if-else-if.
Here is the signature of JavaScript Switch Statement:
switch(expression) { case value1: code that is to be executed; break; case value2: code that is to be executed; break; . . . . default: code that is to be executed if above values are not matched; }
Example 1
<script> var Class='B'; var result; switch(Class) { case 'A': result="A Class"; break; case 'B': result="B Class"; break; case 'C': result="C Class"; break; default: result="No class"; } document.write(result); </script>
Example 2(without using Break)
<script> var Class='B'; var result; switch(Class) { case 'A': result=" A Class"; case 'B': result=" B Class"; case 'C': result=" C Class"; default: result=" No Class"; } document.write(result); </script>
Example 3(Check day and Print Days name)
<script> var day=3; var result; switch(day) { case 1: result="Today is Monday"; break; case 2: result="Today is Tuesday"; break; case 3: result="Today is Wednesday"; break; default: result="Wrongh Choice"; } document.write(result); </script>