Switch Case in Javascript – Learn Javascript Online!

Guys today I am going to tell you about Switch Case in Javascript. Are you aware of it? Hopefully NO, for that reason you are here. Let me tell you about in the details that how it works and how we can use it in our program.

If your program’s output depends on a single variable, then you can control the execution by if else if statement. But do have any other state where you can also control the execution in some more efficient way?

Think!

Right, that is the Switch case. In switch case, you can hold a value of the variable and can control the execution process. So the question arrises that how it is different from if else if? Let me tell you that…

…Before getting into the details, we should have a look on the flow chart of switch case. I’m presenting it here. And please have good eye on it.

Switch Case in Javascript Flowchart.

Switch Case in Javascript Flowchart.

SYNTAX

switch (expression)
{
   case condition 1: statement(s)
   break;
   
   case condition 2: statement(s)
   break;
   ...
   
   case condition n: statement(s)
   break;
   
   default: statement(s)
}

Above I have placed the standard code of switch case. Maybe you are getting a question like why I have used the break? You are right. Why have I used? Let me tell you that…

When any of the above cases will start running if will not stop until you will not use a barrier or a breaker kinda thing. Here that thing is the break. Just write the break and your case will be out.

Now I am giving you an example of switch case in which I’m holding the value of name variable and displaying the result as per the name get fetched by switch case from the variable name.

Switch Case example by Rahul Rahi

Switch Case example by Rahul Rahi

Code is here buddy:

<html>
 <body>
 
 <script type="text/javascript">
 
 var name='pooja';
 document.write("WELCOME TO SWITCH DATABASE <br />");
 switch (name)
 {
 case 'pooja': document.write("Good job Pooja<br />");
 break;
 
 case 'rahul': document.write("Pretty good Rahul<br />");
 break;
 
 case 'sahil': document.write("Passed<br />");
 break;
 
 case 'praveen': document.write("Not so good Praveen<br />");
 break;
 
 case 'aman': document.write("Failed<br />");
 break;
 
 default: document.write("I think you are fired :p<br />")
 }
 document.write("All the best! Do much better than this! My best wishes are with you.");
 
 </script>
 </body>
</html>

 

Leave a Reply

CONTACT ME