switch
statement
When needing to make 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
default
case in aswitch
statement is like the lastelse
in anif
-else
-if
chain. It will be reached if none of the previously tested conditions aretrue
. -
The
break
statement is needed to break out of theswitch
statement. If you omitbreak
,switch
will run all the following cases until it encountersbreak
or exits. This behavior can be useful for grouping cases.
Keep in mind that JavaScript uses strict equality for
switch
statements.