Curriculum Series

What is the purpose of the switch statement?

What is the purpose of the switch statement?

What is the purpose of the switch statement?

JavaScript

The short answer

A switch statement evaluates an expression and executes code based on which case matches. It is an alternative to long if/else if chains when comparing one value against multiple options. Each case needs a break to prevent fall-through.

How it works

javascript
function getDay(num) {
switch (num) {
case 0:
return 'Sunday';
case 1:
return 'Monday';
case 2:
return 'Tuesday';
case 3:
return 'Wednesday';
case 4:
return 'Thursday';
case 5:
return 'Friday';
case 6:
return 'Saturday';
default:
return 'Invalid day';
}
}

switch vs if/else

javascript
// if/else chain — verbose with many conditions
if (status === 'loading') {
showSpinner();
} else if (status === 'success') {
showData();
} else if (status === 'error') {
showError();
} else {
showDefault();
}
// switch — cleaner for many cases
switch (status) {
case 'loading':
showSpinner();
break;
case 'success':
showData();
break;
case 'error':
showError();
break;
default:
showDefault();
}

The fall-through trap

Without break, execution falls through to the next case:

javascript
switch (fruit) {
case 'apple':
console.log('Apple');
// missing break! Falls through to the next case
case 'banana':
console.log('Banana');
break;
}
// If fruit is "apple", prints both "Apple" AND "Banana"

Sometimes fall-through is intentional — for grouping cases:

javascript
switch (day) {
case 'Saturday':
case 'Sunday':
console.log('Weekend');
break;
default:
console.log('Weekday');
}

Important: switch uses strict equality

switch compares with ===, not ==:

javascript
switch (value) {
case '1':
console.log('string');
break;
case 1:
console.log('number');
break;
}
// value = 1 → "number"
// value = '1' → "string"

Interview Tip

Show a basic switch, mention the fall-through trap with break, and note that it uses strict equality. In practice, many developers prefer objects or maps over switch for simple value lookups. Mentioning that alternative shows you think about code style.

Why interviewers ask this

This tests fundamental control flow knowledge. Knowing about fall-through and strict equality shows you understand the details, not just the syntax.

Finished reading?

Mark this topic as solved to track your progress.