Topic 28 of 87
switch Statement
Overview
The switch statement evaluates an expression, matching the expression's value against a series of case clauses. It then executes statements associated with that case.
It is an excellent alternative to writing a long, repetitive chain of else if statements when you are comparing the same variable against many different exact values.
Syntax
Standard Switch Syntax
javascript
const role = "admin";
switch (role) {
case "guest":
console.log("Welcome Guest");
break; // VERY IMPORTANT!
case "admin":
console.log("Full Access Granted"); // This runs
break;
case "superadmin":
console.log("God Mode");
break;
default:
console.log("Unknown Role");
}Grouped Cases
javascript
const fruit = "Apple";
switch (fruit) {
// Groups Apple and Banana together
case "Apple":
case "Banana":
console.log("It's a common fruit.");
break;
default:
console.log("Exotic fruit.");
}Common Pitfalls
- Forgetting the
breakkeyword. If you forget it, the code will "fall through" and execute all the cases below it, regardless of whether they match the condition! This is one of the most common beginner bugs in JS.
Interview Questions
Q:
Does the switch statement use loose (==) or strict (===) equality?
A:
The switch statement uses strict equality (===). This means both the value AND the data type must match exactly. case '1': will not match the integer 1.
Real-World Example
Handling different action types inside a Redux Reducer.
example
javascript
function reducer(state, action) {
switch(action.type) {
case 'INCREMENT':
return { count: state.count + 1 };
case 'DECREMENT':
return { count: state.count - 1 };
default:
return state;
}
}Check Your Knowledge
Test your understanding of switch Statement with these quick questions.