Javascript Switch Case

This Javascript Switch Case acts like a multiple if / else if / else chain. Checks a value against a list of cases, and executes the first case that is true. If no matching case found, it executes the default case. The break(optional) statements with case indicate to the interpreter to end the particular case.

Syntax

<script type="text/javascript">
switch (expression) {
  case case1:
    statements1
    [break;]
  case case2:
    statements2
    [break;]
  case case3:
    statements3
    [break;]
  default:
    default statements
    [break;]
}
</script>

Javascript Switch Case Example 1

<!DOCTYPE html>
<html>
<head>
<title>My first JSON Object Code</title>
<SCRIPT LANGUAGE="JavaScript">
var book = "Commerce";
switch (book) {
  case "English":
    console.log("English book price is $12.");
    break;
  case "Math":
    document.write("Math book price is $22.");
    break;
  case "Commerce":
    document.write("Commerce book price is $12.");
    break;
  case "History":
    document.write("History book price is $125.");
    break;
  case "Physics":
    document.write("Physics book price is $12.99.");
    break;
  default:
    console.log("Sorry, book out of stock");
}
 </SCRIPT>
 </HEAD>
<BODY>
</BODY>
</HTML>

If forget a break which is optional than script will run from the case where condition is met, and will run the case after that regardless if condition was met.

Javascript Switch Case Example 2

<!DOCTYPE html>
<html>
<head>
<title>My first JSON Object Code</title>
<SCRIPT LANGUAGE="JavaScript">
var salary = '50000';
switch (salary)
{
  case '10000': 
	document.write("Assistant");
	break;
  case '20000': 
	document.write("Assistant Manager");
	break;
  case '30000': 
	document.write("Relationship Manager");
	break;
  case '40000': 
  case '50000': 
	document.write("Manager");
	break;
  default:  
	document.write("Unknown post");
}
 </SCRIPT>
 </HEAD>
<BODY>
</BODY>
</HTML>