You can write more than one code block or statement in a switch statement, it works like an if statement, in it you use the break keyword after each statement, if you do not use this keyword, then all the content given in it is displayed in the web page. In addition to the break keyword true condition statement, it stops other content statements from being displayed on the web page, if the condition is false then the default content statement is displayed in the web page.
Syntax
switch(expression){
case value1:
code executed;
break;
case value2:
code executed;
break;
......
default:
code executed (if above values are not matched);
}
Example 1
<!DOCTYPE html> <html> <head> <title></title> </head> <body> <script> var grade = 'C'; var result; switch(grade){ case 'A': result="A Grade"; break; case 'B': result="B Grade"; break; default: result="Grade not matched"; } document.write(result); </script> </body> </html> |
Output
Grade not matched |