Articles → JavaScript → Switch statement in javascript

Switch statement in javascript




Introduction





Prerequisite









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









Sample




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



Demo



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

Query/Feedback


Your Email Id  
 
Subject 
 
Query/FeedbackCharacters remaining 250