You are on page 1of 2

JavaScript Switch Statement

Conditional statements are used to perform different actions based on different


conditions.
The JavaScript Switch Statement
Use the switch statement to select one of many blocks of code to be executed.
Syntax
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
}
This is how it works: First we have a sinle expression n !most often a variable"# that is evaluated
once. The value of the expression is then compared with the values for each case in the structure. $f
there is a match# the block of code associated with that case is executed. Use break to prevent the
code from runnin into the next case automatically.
%xample
<script type="text!a"ascript"#
$%u will recei"e a different &reetin& based
%n what day it is' (%te that )unday=*+
,%nday=1+ -uesday=2+ etc'
"ar d=new .ate();
the.ay=d'&et.ay();
switch (the.ay)
{
case /:
d%cu0ent'write("1inally 1riday");
break;
case 2:
d%cu0ent'write(")uper )aturday");
break;
case *:
d%cu0ent'write(")leepy )unday");
break;
default:
d%cu0ent'write("340 l%%kin& f%rward t% this weekend5");
}
<script#

You might also like