• USA : +1 973 910 5725
  • INDIA: +91 905 291 3388
  • info@tekslate.com
  • Login

JavaScript Switch Case

JavaScript Switch Case

You can use multiple  if… else if statement, as in previous chapter, to perform a multi way branch. However, this is not always the best solution, especially when all of the branches depend on the value of a single variable.

Starting with JavaScript 1.2, you can use a SWITCH statement which handles exactly this situation, and it does so more efficiently than repeated if..else if statements.

 

Syntax 

The basic syntax of the switch statement is to give an expression to evaluate and several different statements to execute based on the value of the expression. The interpreter checks each case against the value of the expression until a match is found, if nothing matches, a default condition will be used.

 

Switch(expression)

{

case   condition 1 : statement(s)

break;

Case condition 2: statement(s)

break;

Case condition n: statement(s)

break;

default:  statement(s)

 

 break

statements indicate to the interpreter the end of that particular case. If they were omitted, the interpreter would continue executing each statement in each of the following cases

We will explain break statement in LOOP Control chapter.

 

Example

Following example illustrates a basic while loop:

<script type=”text/javascript”>

<!—

var grade=’A’;

document.write(“Entering switch block <br/>”);

switch(grade)

{

case   ‘A’ : document.write(“Good job<br />”);

break;

Case   ‘B’ :doucument.write(“Pretty good  <br/>”);

break;

case    ‘C’: document.write(“Passed<br />”);

break;

Case    ‘D’ :document.write(“Not So good <br/>”);

break;

Case     ‘F’ :documenet.write(“Failed <br/>”);

break;

default :document.write(“Unknown grade<br/>”)

break;

}

document.write(“Existing switch block”);

//– >

</script>

 

Example

Consider a case if you do not use break statement:

<script type=”text/javascript”>

<!—

var grade=’A’;

document.write(“Entering switch block<br/>”);

switch(grade)

{

Case ‘A’ :document.write(“Good job <br />”);

Case ‘B’ :document.write(“Pretty good <br />”);

Case ‘C’ :document.write(“Passed<br/>”);

Case ‘D’ :document.write(“Not So good <br />”);

Case ‘F’ :document.write(“Failed <br />”);

default: document.write(“Unknown grade<br/>”);

}

document.write(“Existing switch block”);

//– >

</script>

Summary
Review Date
Reviewed Item
JavaScript Switch Case
Author Rating
5

“At TekSlate, we are trying to create high quality tutorials and articles, if you think any information is incorrect or want to add anything to the article, please feel free to get in touch with us at info@tekslate.com, we will update the article in 24 hours.”

0 Responses on JavaScript Switch Case"

Leave a Message

Your email address will not be published. Required fields are marked *

Site Disclaimer, Copyright © 2016 - All Rights Reserved.