Javascript Switch Case

This 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>

Example1

<!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>
Try Now

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.

Example2

<!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>
Try Now

See Also

Javascript Built in String Object
Javascript Built in Number Object
Javascript Built in Math Object
Javascript Built in Date Object
Javascript Built in Arrays Object
Javascript Built in Boolean Object
Javascript Built in RegExp Object
Javascript Built in JSON Object


 
SHARE THIS IF YOU LIKE!
submit to reddit
SUBSCRIBE FOR LATEST UPDATES
HAVE WE CONNECTED ON FACEBOOK?
TOP TUTORIALSTOP CODE EXAMPLESTOP LIVE DEMOLINKSSTAY CONNECTED
HTML Tutorial
HTML5 Tutorial
Bootstrap3 Tutorial
Javascript Tutorial
TypeScript Tutorial
AngularJS Tutorial
CSharp Tutorial
PHP Tutorial
Developer Tools
Javascript
AngularJS
Google MAP API V3
ASP.NET
Javascript
AngularJS
Google MAP API V3
Contact Us
Advertise with Us
Privacy Policy
Disclaimer
Stay connected. We actually like you. If you want to get up to the minute updates, then connect with us on your fav below.
 
Twitter   Linkedin   Facebook   Google+    RSS   Pinterest
 
Protected by Copyscape Original Content Checker
 
 
Copyright ©2017 www.techstrikers.com Unauthorized reproduction/replication of any part of this site is prohibited.