A switch statement is the same as to many if statements put together. It has the following syntax:
switch (condition) { case 'some-value': // Do something break default: // Do something break}switchwill run if theconditionevaluates totrue.casetests whether the condition is strictly equal to a value.breakends theswitchstatement
The most common use-case for switch is to check whether a string is a certain value.
const hobby = 'some-value'
switch (hobby) { case 'basketball': // Do stuff if hobby === 'basketball' break case 'soccer': // Do stuff if hobby === 'soccer' break default: // Do stuff hobby is neither basketball nor soccer}Doing the same thing for many cases
You can do the same thing for many cases if you omit the break keyword. Here’s an example:
switch (hobby) { case 'basketball': case 'soccer': categorizeUnderBallRelatedSports() break default: // Something else}Semicolons
If you run a single function within each case, it may be neater to use a semicolon to separate lines of code.
switch (hobby) { case 'basketball': basketball() break case 'soccer': soccer() break default: // Do stuff hobby is neither basketball nor soccer}Switch vs if
I prefer using if statements over switch statements. I only use switch when I want to use early returns, but I can’t.
We’ll see an example of this in the next lesson when refactoring the calculator.
Welcome! Unfortunately, you don’t have access to this lesson. To get access, please purchase the course or enroll in Magical Dev School.
Unlock this lesson