The JavaScript switch statement is used to execute one code from multiple expressions. It is just like else if statement that we have learned in previous page.
Syntax for javascript switch statement
switch(expression){
case value1:
code to be executed;
break;
case value2:
code to be executed;
break;
......
default:
code to be executed if above values are not matched;
}
Example:
<script>
var color='C';
var result;
switch(color){
case 'A':
result="one";
break;
case 'B':
result="two";
break;
case 'C':
result="three";
break;
default:
result="No Color";
}
document.write(result);
</script>
var color='C';
var result;
switch(color){
case 'A':
result="one";
break;
case 'B':
result="two";
break;
case 'C':
result="three";
break;
default:
result="No Color";
}
document.write(result);
</script>
Output: three
Here the default keyword specifies the code to run if there is no
case match