Decisions and repetition
The JavaScript Switch Conditional
Learn how the JavaScript switch conditional picks one case to run based on an expression, why each case needs a break, and how return works inside a function.
if/else chains work well for a few branches. With many discrete values, a switch reads cleaner.
Syntax:
switch(<expression>) {
//cases
}
JavaScript compares the expression to each case label and runs the first match:
const a = 2
switch(a) {
case 1:
//handle case a is 1
break
case 2:
//handle case a is 2
break
case 3:
//handle case a is 3
break
}
Without break, execution falls through into the next case. Sometimes that is intentional. Usually it is a bug.
Inside a function you can return instead of break:
const doSomething = (a) => {
switch(a) {
case 1:
//handle case a is 1
return 'handled 1'
case 2:
//handle case a is 2
return 'handled 2'
case 3:
//handle case a is 3
return 'handled 3'
}
}
Add default for values no case handles:
const a = 2
switch(a) {
case 1:
//handle case a is 1
break
case 2:
//handle case a is 2
break
case 3:
//handle case a is 3
break
default:
//handle all other cases
break
}
switch works best when every branch compares the same expression to constant values. If each branch needs a different variable or range check, if/else is usually clearer.
Fall-through can be useful when several cases share one block:
switch (status) {
case 'draft':
case 'review':
notify('Still in progress')
break
case 'published':
notify('Live')
break
}
Here 'draft' and 'review' run the same code because neither case includes break.
switch uses strict equality (===). '2' does not match 2.
Keep case labels simple constants: numbers, strings, or symbols. Complex expressions belong in if/else.
When a function returns from every branch, you often skip default entirely. When you keep default, use it for unexpected input and log or throw so bugs surface early.
Remember that break only exits the switch. It does not exit the surrounding function unless you return from inside the case.
A common mistake is forgetting break after the last case before default. Execution falls into default even when you matched an earlier case.
Document intentional fall-through with a comment so the next reader knows you meant it.
When the same action applies to many cases, fall-through beats copying the same block ten times.
Try a switch on the strings 'draft', 'published', and 'archived'. Log a message for each status and use default for unknown values.
Lesson completed