Javascript TUTORIAL


Javascript switch statement


There are instances when you have to write a code which will have endless "if" ..."else if" ... "else if" statements. While you can do like this, javascipt provide a switch statement that makes the code look cleaner.

Let us look at the example the prints the day of the week.

  1. <html>
  2. <body>
  3. <script type="text/javascript">
  4. <!--
  5. /*
  6. ********************************************************
  7. Example switch statement
  8. ********************************************************
  9. */
  10. var day = new Date();
  11. myday = day.getDay();
  12. switch (myday)
  13. {
  14. case 0:
  15. document.write("Today is Sunday");
  16. break;
  17. case 1:
  18. document.write("Today is Monday");
  19. break;
  20. case 2:
  21. document.write("Today is Tuesday");
  22. break;
  23. case 3:
  24. document.write("Today is Wednesday");
  25. break;
  26. case 4:
  27. document.write("Today is Thursday");
  28. break;
  29. case 5:
  30. document.write("Today is Friday");
  31. break;
  32. default:
  33. document.write("Today is Saturday");
  34. }
  35.  
  36. //-->
  37. </script>
  38. </body>
  39. </html>


If you run the above script it should display the day of the week.

Notice that we have made the use of the inbuilt javascript date object and the inbuilt day function to retrieve the today's date and day. Do not wrorry about the in buiilt code function for now. We will come to that later.

 var day = new Date();
 myday = day.getDay(); 


You can try this example online here.

Javascript switch Example

Javascript switch statement


For those who would like to refer to the Syntax of the switch statements here is it



switch(n)
{
case 1:
execute code block 1
break;
case 2:
execute code block 2
break;
default:
code to be executed if n is
different from case 1 and 2
}



We have only small details of switch statement. To read more about it you may check the following topics.
More Array Topics
Case statement sharing code
Switch type mismatch
switch break
switch vs if