Switch-Case Statement
Switch-case statement is used to execute a block of code among one or more, based on the value of an expression.
Syntax
switch (expression) {
case a:
//code
break;
case b:
//code
break;
default:
//code
}
switch
is keyword.expression
is any expression that evaluates to a values.case
is keyword.a
is value that the expression’s result would be matched against.b
is value that the expression’s result would be matched against.code
is any valid JavaScript code.break
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");
}