JavaScript fundamentals / 04
switch statements
Understand case, default, break, and fall-through, and compare switch with if/else.
On this page
switch and if
Before introducing the syntax, the original lesson compares switch with a sequence of if statements. It describes an instruction as a command the CPU reads from memory and argues that repeated if checks require more instructions, while a switch checks its input once. On that basis, it recommends switch when there are many cases.
Editorial correction: that performance explanation is too general. JavaScript engine optimizations, the case values, and the surrounding code determine the actual cost. A
switchis not guaranteed to use fewer instructions or be faster. Choose the form that clearly expresses the logic, and measure when performance matters.
The structure of switch
A switch usually contains one or more case clauses and may include a default. Think of default as the counterpart to a final else: it runs when no case matches.
Put the value to inspect inside the parentheses after switch. Each case supplies a value to match and statements to run. A break ordinarily ends the selected branch and exits the switch.
If you omit break, execution can continue into the next case's statements. This is called fall-through.
Walk through the example
In the original example, a is 4:
- If
ais1, print"a = 1"and exit. - If
ais2, print"a = 2"and exit. - If
ais3, print"a = 3"and exit. - Otherwise, the
defaultprints"not 1, 2, 3"and exits.
Open the original switch example on CodePen.
The next lesson covers loops.
Moved here from Tistory
I migrated this post from my Korean Tistory blog, I am Jason Lee, to this website and translated it into English. My writing and projects now live together in one place.
The original publication date, code examples, and screenshots are preserved. Editorial notes clarify known issues in the original material.
Original post on Tistory English edition · Aug 30, 2026