Switch-Case Statement
switch (expression) {
case a:
//code
break;
case b:
//code
break;
default:
//code
}
switch
is keywordexpression
is any expression that evaluates to a valuescase
is keyworda
is value that the expression’s result would be matched againstb
is value that the expression’s result would be matched againstcode
is any valid JavaScript codebreak
is the statement to break the switch-case statement
the expression
is evaluated, and is compared with the case
values. if there is a match, then the respective code
block is executed. if there is no match, then the default
block is executed
Examples
1. printing the number in text based on the number’s value
a = 2
switch (a) {
case 0:
console.log("zero");
break;
case 1:
console.log("one");
break;
case 2:
console.log("two");
break;
case 3:
console.log("three");
break;
case 4:
console.log("four");
break;
default:
console.log("unknown number");
}