JavaScript Control Flow Conditionals
Switch
A growing list of if and else-if statements tend to get hairy real
fast. Especially if all we're doing is a bunch of equality
checks. That's where the switch statement comes in and saves the
day. Switch statements are great for situations where you want to
conditionally handle a fixed set of values.
A switch statement evaluates an expression, and matches its value with
a list of case values, selects the first case that matches and
executes the statements in that case as well as the cases that
follow. We can limit the number of following cases executed with the
break statement which tells JavaScript to not execute any more of
the following cases.
switch (expression) {case value1:// case body// falls through to the next case// because there is no 'break' within// this case bodycase value2: {// case body// code blockbreak}default:// if no other cases match}
The case body can, but doesn't have to, be a code block if we want to define constants and variables in their own little scope.
Fallthrough
Switch cases fall through to the cases that follow until a break
statement is met or we have reached end of the list of cases.
const x = 2switch (x) {case 1:console.log(1)case 2:console.log(2)case 3:console.log(3)breakcase 4:console.log(4)}
The switch above will match case 2 and execute both its body and the
next case body (case 3) where it meets a break statement and
stops.
Why use switch?
if (fn(arg) === 1) {// code for 1} else if (fn(arg) === 2) {// code for 2} else if (fn(arg) === 3) {// code for 3} else if (fn(arg) === 4) {// code for 4} else {// code for other}
Notice how repetitive our conditions are, and how many times we
potentially execute fn(arg) in them. We could rewrite with the
function call already evaluated before the if statement to improve
performance as shown below.
const condExpr = fn(arg)if (condExpr === 1) {// code for 1} else if (condExpr === 2) {// code for 2} else if (condExpr === 3) {// code for 3} else if (condExpr === 4) {// code for 4} else {// code for other}
We have improved performance, but the repetition is still there. Let us now convert this to a switch based solution.
switch (fn(arg)) {case 1: {// code for 1break}case 2: {// code for 2break}case 3: {// code for 3break}case 4: {// code for 4break}default: {// code for other}}
The switch based solution is optimal in this case as it automatically improves performance and reduces error-prone repetition.
Read more on MDN
switch