JavaScript Switch

The JavaScript switch statement is used to execute one code from multiple expressions. It is just like else if statement that we have learned in previous page. But it is convenient than if..else..if because it can be used with numbers, characters etc.
The objective of a switch statement is to give an expression to evaluate and several different statements to execute based on the value of the expression. The interpreter checks each case against the value of the expression until a match is found. If nothing matches, a default condition will be used.

Syntax:

switch (expression) {
case condition 1: statement 1
break;
case condition 2: statement 2
break;
case condition 3: statement 3
break;
...
case condition n: statement n
break;
default: statement
break;
}

The break statements indicate the end of a particular case. If they were omitted, the interpreter would continue executing each statement in each of the following cases.

Example:

var grade = 'A';
switch (grade) {
case 'A': document.write ("Good job");
break;
case 'B': document.write ("Pretty good");
break;
case 'C': document.write ("Passed");
break;
case 'D': document.write ("Not so good");
break;
case 'F': document.write ("Failed");
break;
default : document.write ("Unknown");
}

Run Example