|
| SWITCH STATEMENTS IN JAVASCRIPT
A switch statement in javascript can be used when you test a variable and need to have various statement blocks to execute dependent on what the variable matches to. A switch statement is ideal to use if you find that you have too many if statements that can become confusing and cumbersome.
The general format is:
switch(variable)
{
case ('option1'):
execute this code
break;
case ('option2'):
execute this other code
break;
default:
execute this code if none of the above options match
}
You can use many cases as you like - there is no limit. The default option will apply if none of the other cases match. The use of break; after each code to execute will stop the script from executing further after it finds a match.
Example:
var username="susan101";
switch(username)
{
case ('kyle4life'):
alert('Hello Kyle');
break;
case ('susan10'):
alert('Hello Susan');
break;
default:
alert('You are not welcome here');
}
The code above can is explained as follows:
If username is kyle4life, then an alert Hello Kyle is outputted.
If username is susan10, then an alert Hello Susan is outputted.
If username is neither of the previous cases ie. neither kyle4life nor susan10, then You are not welcome here is outputted.
In the above example You are not welcome here is outputted as username is declared as susan101 and no cases match.
 |
|
|