Question:
What is a switch-case statement?
Answer:
A switch-case statement is a way to write several else-if expressions as one list.
Question:
How do I write a switch-case statement?
Answer:
The syntax is the keyword switch, followed by an expression inside parentheses, followed by
open and close curly-braces. Inside the curly-braces are several case statements.
The syntax for each case statement is the keyword case, followed by a value,
followed by a colon, followed one or more statements to be executed if the case expression is true,
followed by the keyword break.
After all case statements, it is recommended to provide a default statement, whose syntax is the keyword default,
followed by a colon, followed by one or more statements to be executed
if none of the case statements were executed. For example:
var AdmitEarly;
var Discount;
var Membership = "Gold";
switch ( Membership.toUpperCase() ) {
case "SILVER":
Discount = 1.50;
AdmitEarly = true;
break;
case "GOLD":
Discount = 2.00;
AdmitEarly = true;
break;
case "PLATINUM":
Discount = 2.50;
AdmitEarly = true;
break;
default:
Discount = 0;
AdmitEarly = false;
}
Notice that:
- You do not use curly-braces to contain multiple statements for each case expression.
- The default keyword acts like the else keyword for an if statement.
If none of the above is true, the default statement will execute.
- Once a break statement is encountered, your code exits the switch-case statement.
Therefore, statements for only one case expression, (or default), will execute.
Question:
Can I test for more than one value using case?
Answer:
Yes. Consider the following example:
var TestGrade;
var IncorrectAnswers = 3;
switch (IncorrectAnswers) {
case 0:
case 1:
TestGrade = "A";
break;
case 2:
case 3:
TestGrade = "B";
break;
case 4:
case 5:
case 6:
TestGrade = "C";
break;
case 7:
case 8:
TestGrade = "D";
break;
default:
TestGrade = "F";
}
Notice that you cannot write complex case expressions using <, <=, && ...
If your logic requires testing for a broad range of values, then you would use
if / else-if statements.