The switch statement
Hey ,
I'm thrilled to help you learn JavaScript. Unfortunately, you've landed on a page where you cannot access with your current purchase.
Please upgrade (use this link) access this content.
I'm super eager to help you learn more!
The switch statement
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;
}
switch
will run if the condition
evaluates to true
.
case
tests whether the condition is strictly equal to a value.
break
ends the switch
statement
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.