Using switch
Statements in JavaScript
In this video, I cover how to use the switch
statement as an alternative to if / else if / else
chains. The switch
statement can make your code easier to read when you're checking the same variable against multiple values.
Basic Syntax of a switch
Statement
1const myNumber = 10;
2
3switch (myNumber) {
4 case 9:
5 console.log("My number is 9 for sure");
6 break;
7 case 10:
8 console.log("My number is 10 for sure");
9 break;
10 case 11:
11 console.log("My number is 11 for sure");
12 break;
13 default:
14 console.log("Unhandled");
15 break;
16}
How It Works
- The
switch
keyword evaluates the expression inside the parentheses—in this case, myNumber
.
- It compares the value against each
case
.
- If a match is found, that block runs.
- The
break
statement prevents the remaining cases from running (important!).
- If no match is found, the
default
block runs.
Equivalent if / else if / else
Version
1if (myNumber === 9) {
2 console.log("My number is 9 for sure");
3} else if (myNumber === 10) {
4 console.log("My number is 10 for sure");
5} else if (myNumber === 11) {
6 console.log("My number is 11 for sure");
7} else {
8 console.log("Unhandled");
9}
Both versions do the same thing—it's mostly a matter of preference.
Why Use break
?
Without break
, JavaScript will continue running the code in the next cases, even if the condition was already met:
1switch (myNumber) {
2 case 10:
3 console.log("Matched 10");
4 case 11:
5 console.log("Also runs 11"); // This will run too if break is missing
6}
To avoid unintended behavior, always include break
after each case unless you specifically want fall-through behavior.
The default
Case
- Acts like the
else
block in an if
statement.
- It catches any unhandled or unexpected values.
- Always include it to handle edge cases or invalid input gracefully.
Summary
- Use
switch
when checking the same variable against multiple values.
- Use
break
to prevent fall-through.
- Include a
default
to handle unknown values.
- Both
switch
and if / else if / else
are valid—use whichever improves readability for your use case.
That's it for the switch
statement. See you in the next video!