EN
JavaScript - switch statement with example
4 points
The switch
statement is used to select and execute some code blocks from defined cases using expression.
xxxxxxxxxx
1
switch(expression) {
2
case x:
3
// code block
4
break;
5
case y:
6
// code block
7
break;
8
case z:
9
// code block
10
break;
11
12
// other cases...
13
14
default:
15
// code block
16
}
Where:
expression
returns a value that will be compared with cases,x
,y
andz
are values that are associated with code blocks,- if
expression
maches some case value (x
,y
orz
) than related code block is executed, - if break instruction is placed after a code block, the next code block is not executed,
- if
expression
is not matched to any case value default code block is executed.
xxxxxxxxxx
1
var name = 'John';
2
var role = '';
3
4
switch (name) {
5
case 'John':
6
role = 'Administrator';
7
break;
8
case 'Kate':
9
case 'Chris':
10
role = 'Moderator';
11
break;
12
default:
13
role = 'User';
14
break;
15
}
16
17
console.log('User ' + name + ' is ' + role + '.');
Output:
xxxxxxxxxx
1
User John is Administrator.