We recently looked at if statements, but now it’s time to switch things up! We’d look to use the switch
statement whenever we have multiple test cases for a particular expression. If you find yourself writing multiple if/else
statements, this may be worth condensing into a switch
statement.
As a result, in many ways, the switch
statement is similar to the if
statement:
- The switch statement firstly evaluates an expression.
- Using
case
syntax, it compares the result of the expression with the particular case. - It then executes any code inside of the
case
until the break
keyword is found. If the break
keyword is not added to the case, it’ll continue to execute further code within the block. - Alternatively, if there are no matching cases, an optional
default
case can be added to execute a block of code regardless.
🐊 Alligator.io recommends:
ES6 for Everyone → A video course to learn modern JavaScript
ⓘ About this affiliate link
Let’s look at a version of this in code:
const sky = "blue"; switch (sky) { case "red": console.log("Uh oh."); break; case "blue": console.log("A good day for golf!"); break; default: console.log("Try looking up for a hint."); }
As the value of sky
is equal to blue
, the case blue
is executed. However, if we changed the value of sky
to an empty string ""
we’d get the default
case.
Here’s the same example, with a little twist:
const sky = "blue"; switch (sky) { case "red": case "purple": case "yellow": case "green": console.log("Uh oh."); break; case "blue": console.log("A good day for golf!"); break; default: console.log("Try looking up for a hint."); }
As you can see in this second example, it’s perfectly valid to have multiple case statements that share the same block of executed code.
Summary
You should now have the hang of switch
statements within JavaScript. Use this new power wisely - don’t turn every if
statement into a switch
, only those that are getting too long to read tersely. And don’t forget to break
out of the switch statement once you’ve found the right condition, otherwise the rest of the code will run and have an impact on your code’s performance. default
doesn’t need a break
statement, because if your code reaches that point, it has already gone through the whole code of the switch case anyway.