JavaScript Switch Case

switch case in javascript

The JavaScript Switch Case statement is used to perform different actions based on different conditions.


Flow Chart of JavaScript Switch Case:


Let’s see the simple example of switch statement in java script.

<script>

var grade='B';

var result;

switch(grade){

case 'A':

result="A Grade";

break;

case 'B':

result="B Grade";

break;

case 'C':

result="C Grade";

break;

default:

result="No Grade";

}

document.write(result);

</script>

The Break Keyword

When Java Script code reaches a break keyword, it breaks out of the switch block. This will stop the execution of more code and case testing inside the block.


The default Keyword

The default keyword specifies the code to run if there is no case match.

 var color ="yellow";

switch(color) {

   case "blue": 

     document.write("This is blue.");

     break;

   case "red": 

     document.write("This is red.");

     break;

   case "green": 

     document.write("This is green."); 

     break;

   case "orange": 

      document.write("This is orange."); 

      break;

   default: 

      document.write("Color not found.");

}



//Outputs "Color not found."

Spread the love

Leave a Comment

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