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.
1. switch syntax
switch(expression) {
case x:
// code block
break;
case y:
// code block
break;
case z:
// code block
break;
// other cases...
default:
// code block
}
Where:
expressionreturns a value that will be comparedĀ with cases,x,yandĀzareĀ valuesĀ that are associatedĀ with code blocks,- if
expressionmaches some case value (x,yorz) than related code block is executed, - if breakĀ instruction is placed after a code block, the next code block is not executed,
- if
expressionis not matched to any case value default code block is executed.
2. switch statement example
// ONLINE-RUNNER:browser;
var name = 'John';
var role = '';
switch (name) {
case 'John':
role = 'Administrator';
break;
case 'Kate':
case 'Chris':
role = 'Moderator';
break;
default:
role = 'User';
break;
}
console.log('User ' + name + ' is ' + role + '.');
Output:
User John is Administrator.