Switch-case

If you have more than three conditions, it is good practice to use the switch-case statement. The basic structure of switch-case is as shown in the following:

switch (expression) {
  case expression1:
    break;
  case expression2:
    break;
  case expression3:
    break;
//-------------------------------
//-------------------------------
//  More case
//-------------------------------
//  -------------------------------
  default:    
}

Every case has a break. However, the default does not need a break.

Consider that Tom has 35 pens. His friends John, Cindy, Laura, and Terry have 25, 35, 15, and 18 pens, respectively. Now, John wants to check who has 35 pens. We need to compare the number of Tom's pens with everyone's pens. We can use switch-case for this type of case. The code will be as follows:

<html>
  <head>
    <title>
      Switch-Case
    </title>
  </head>
  <body>
    <script type="text/javascript">
      var Tom = 35;
      switch (Tom) {
        case 25: //Number of John's pens
          document.write("John has equal number of pens as Tom");
        break;
        case 35: //Number of Cindy's pens
          document.write("Cindy has equal number of pens as Tom");
        break;
        case 15: //Number of Laura's pens
          document.write("Laura has equal number of pens as Tom");
        break;
        case 18: //Number of Terry's pens
          document.write("Terry has equal number of pens as Tom");
        break; 
        default:
          document.write("No one has equal pens as Tom");
      }
    </script>
  </body>
</html>

The output will be as follows:

Switch-case

Note

Now, change the value of second case (35) to other and check your result.

Exercise

  1. Suppose you need to go to school every day except Saturday and Sunday. Write a code, where you will input today's date number and the web page will show you whether you need to go to school or not. (Hint: use a switch case.)
  2. Consider that you have a garden and you water all the plants on even days of the month. Write a code that will show you whether you will water your plants on that day. (Hint: use the if condition and modulus operator (%).)
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset