JavaScript Switch Statement.

Posted on 19/09/2009 by

1



This is basically used to switch the statement to select one of many blocks of code to be executed.

Actually this is how it works… First we have a single expression n (its mostly often a variable) that is evaluated one. The value of the expression is then compared with the values for each case in the structure. If there is a match, the block of code is joint with that case is executed. Use the BREAK to prevent the code from running into the next case automatically.

Example1:

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
}

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 }

Example2:

The Input

<html>
<body>
<script type=”text/javascript”>
var d = new Date();
theDay=d.getDay();
switch (theDay)
{
case 5:
document.write(“<b>Finally Friday</b>”);
break;
case 6:
document.write(“<b>Sleepy Saturday</b>”);
break;
case 0:
document.write(“<b>Sexy Saturday,</b>”);
document.write(“<b>Super Sunday,</b>”);
document.write(“<b>Monday Morning Blues,</b”);
document.write(“<b>Terrific Tuesday,</b”);
document.write(“<b>Weird Wednesday,</b”);
document.write(“<b>Tipsy Thursday</b”);
document.write(“<b>And Finally Friday</b”);
break;
default:
document.write(“<b>I’m really looking forward to this weekend!</b>”);
}
</script>

<p>This JavaScript will give you a different greetings based on what day it is. Note that Sunday=0, Monday=1, Tuesday=2, etc.</p>
</body>
</html>

The Output

Sexy Saturday,Super Sunday,Monday Morning Blues,Terrific Tuesday,Weird Wednesday,Tipsy ThursdayAnd Finally Friday

This JavaScript will generate a different greeting based on what day it is. Note that Sunday=0, Monday=1, Tuesday=2, etc.

EllaHax

Advertisements
Posted in: Coding, JavaScript