Articles → JavaScript → Switch Statement In Javascript

Switch Statement In Javascript






Purpose





Syntax


switch (n) {
    case 1:
        //execute code block 1
        break;
    case 2:
        //execute code block 2
        break;……….
        default:
            //  execute code block 3
}











If-Else Vs Switch


  1. Switch is more logical in syntax as compared to if-else
  2. Switch is quicker in execution

Example




<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
   <head>
      <title>Switch demo page</title>
   </head>
   <body>
      <div id="dateDiv" style="background-color: Green; color: White;">
      </div>
      <script language="javascript" type="text/javascript">
         var dateDiv = document.getElementById("dateDiv");
         //  Write the logic for date
         var d = new Date();
         switch (d.getDay()) {
             case 0:
                 dateDiv.innerHTML = "Sunday";
                 break;
             case 1:
                 dateDiv.innerHTML = "Monday";
                 break;
             case 2:
                 dateDiv.innerHTML = "Tuesday";
                 break;
             case 3:
                 dateDiv.innerHTML = "Wednesday";
                 break;
             case 4:
                 dateDiv.innerHTML = "Thursday";
                 break;
             case 5:
                 dateDiv.innerHTML = "Friday";
                 break;
             case 6:
                 dateDiv.innerHTML = "Saturday";
                 break;
         }        
      </script>
   </body>
</html>



Try It


Posted By  -  Karan Gupta
 
Posted On  -  Thursday, November 3, 2011

Query/Feedback


Your Email Id  
 
Subject 
 
Query/FeedbackCharacters remaining 250