Branching using a switch statement
JavaScript also has a switch
statement that allows branching to occur based on the value of a (not necessarily Boolean) expression. Each case
specifies a possible value of the expression, followed by any number of statements to be executed if the expression has that value, followed by break
. For example, if the expression evaluates to a number, the values are numbers, and if the expression evaluates to a string, the values are strings.
The optional default
case, if included, is taken if none of the other cases apply.
switch(expression) {
case value1:
statement1;
break;
case value2:
statement2;
break;
case value3:
statement3;
break;
default:
statement4;
break;
}