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.
|
<html> <body> <script type="text/javascript"> <!-- /* ******************************************************** Example switch statement ******************************************************** */ var day = new Date(); myday = day.getDay(); switch (myday) { case 0: document.write("Today is Sunday"); break; case 1: document.write("Today is Monday"); break; case 2: document.write("Today is Tuesday"); break; case 3: document.write("Today is Wednesday"); break; case 4: document.write("Today is Thursday"); break; case 5: document.write("Today is Friday"); break; default: document.write("Today is Saturday"); } //--> </script> </body> </html> |
If you run the above script it should display the day of the week.
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 } |