What is the purpose of the switch statement?
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
1function getDay(num) {2 switch (num) {3 case 0:4 return 'Sunday';5 case 1:6 return 'Monday';7 case 2:8 return 'Tuesday';9 case 3:10 return 'Wednesday';11 case 4:12 return 'Thursday';13 case 5:14 return 'Friday';15 case 6:16 return 'Saturday';17 default:18 return 'Invalid day';19 }20}
switch vs if/else
1// if/else chain — verbose with many conditions2if (status === 'loading') {3 showSpinner();4} else if (status === 'success') {5 showData();6} else if (status === 'error') {7 showError();8} else {9 showDefault();10}1112// switch — cleaner for many cases13switch (status) {14 case 'loading':15 showSpinner();16 break;17 case 'success':18 showData();19 break;20 case 'error':21 showError();22 break;23 default:24 showDefault();25}
The fall-through trap
Without break, execution falls through to the next case:
1switch (fruit) {2 case 'apple':3 console.log('Apple');4 // missing break! Falls through to the next case5 case 'banana':6 console.log('Banana');7 break;8}9// If fruit is "apple", prints both "Apple" AND "Banana"
Sometimes fall-through is intentional — for grouping cases:
1switch (day) {2 case 'Saturday':3 case 'Sunday':4 console.log('Weekend');5 break;6 default:7 console.log('Weekday');8}
Important: switch uses strict equality
switch compares with ===, not ==:
1switch (value) {2 case '1':3 console.log('string');4 break;5 case 1:6 console.log('number');7 break;8}9// value = 1 → "number"10// 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.