switch statement
When needing to do a lot of comparisons for a single value, instead of using many if-else-if statements, you can use the switch statement:
const letter = "B-"; let gpa; switch (letter) { case "A+": case "A": gpa = 4.0; break; case "A-": gpa = 3.7; break; case "B+": gpa = 3.3; break; case "B": gpa = 3.0; break; case "B-": gpa = 2.7; break; case "C+": gpa = 2.3; break; case "C": gpa = 2.0; break; case "C-": gpa = 1.7; break; case "D+": gpa = 1.3; break; case "D": gpa = 1.0; break; case "D-": gpa = 0.7; break; case "F": gpa = 0.0; break; default: gpa = null; } if (gpa !== null) { console.log("Your GPA is " + gpa); } else { console.error(letter + " cannot be converted to GPA value"); }
-
The
defaultcase in aswitchstatement is like the lastelsein anif-else-ifchain. It will be reached if none of the previously tested conditions aretrue. -
The
breakstatement is needed to break out of theswitchstatement. In case you omitbreak,switchwill run all the following cases until it encountersbreakor exits. This can be useful for grouping cases.
Keep in mind that JavaScript uses strict equality for
switchstatements.