Javascript TUTORIAL


Switch statement sharing same code


If you have a the switch statement where several switch 'cases' share same properties, then we can combine them in such a way that only that switch statement need to have the code.

Let us take a look at the example where we find if the height of a person given in inches is less than, equal to or greater than 5 feet.

  1. <html>
  2. <body>
  3. <script type="text/javascript">
  4. <!--
  5. /*
  6. ********************************************************
  7. Reference Designer.com
  8. Example switch statement
  9. ********************************************************
  10. */
  11. var height = 62;
  12.  
  13.  
  14. switch (height)
  15. {
  16. case 58:
  17. case 59:
  18. document.write("Height is less than 5 feet");
  19. break;
  20. case 60:
  21. document.write("Height is equal to 5 feet");
  22. break;
  23. case 61:
  24. case 62:
  25. case 63:
  26. document.write("height is more than 5 feet");
  27. break;
  28. default:
  29. document.write("height is out of 58 inch to 63 inch ranhe");
  30. }
  31.  
  32. //-->
  33. </script>
  34. </body>
  35. </html>


You can try this example online here.

Javascript switch Combime similar statements

- If the height is 58 or 59, the case statement next to 59 is executed.
- If the height is 61,62 or 63, the case statement next to 63 is executed.

Rest of the code is self explanatory.

You may be tempted to think that you can combine two case options using and OR operator as in

  1. case 58 || 59:
  2. document.write("Height is less than 5 feet");
  3. break;


or, using a list of options in this manner

  1. case 58 , 59:
  2. document.write("Height is less than 5 feet");
  3. break;


Both of these are syntactically incorrect.