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