JavaScript switch Statement
The switch statement is used to perform different actions based on different conditions.
JavaScript switch Statement
Use the switch statement to select one of several code blocks to execute.
Syntax
switch
(
n
)
{
case
1
: execute the code block
1
break
;
case
2
: execute the code block
2
break
;
default
: Similar to
case
1
and
case
2
Code that runs when no case matches
}
How it works: First, set the expression n(usually a variable). Then the value of the expression is compared with the value of each case in the structure. If there is a match, the code block associated with that case is executed. Use **break ** to prevent the code from automatically running into the next case.
Example
Display the name of the current weekday. Note that Sunday=0, Monday=1, Tuesday=2, and so on:
var
d
=
new
Date
(
)
.
getDay
(
)
;
switch
(
d
)
{
case
0
:
x
=
"
Today is Sunday
"
;
break
;
case
1
:
x
=
"
Today is Monday
"
;
break
;
case
2
:
x
=
"
Today is Tuesday
"
;
break
;
case
3
:
x
=
"
Today is Wednesday
"
;
break
;
case
4
:
x
=
"
Today is Thursday
"
;
break
;
case
5
:
x
=
"
Today is Friday
"
;
break
;
case
6
:
x
=
"
Today is Saturday
"
;
break
;
}
x The result of running:
Try it »
The default keyword
Use the default keyword to specify what to do when no match exists:
Example
If today is neither Saturday nor Sunday, a default message is output:
var
d
=
new
Date
(
)
.
getDay
(
)
;
switch
(
d
)
{
case
6
:
x
=
"
Today is Saturday
"
;
break
;
case
0
:
x
=
"
Today is Sunday
"
;
break
;
default
:
x
=
"
Looking forward to the weekend
"
;
}
document
.
getElementById
(
"
demo
"
)
.
innerHTML
=
x
;
x The result of running:
Try it »