JavaScript Internals (521 Qs)•Part 4: Prototypes, Object Methods & Event Loop (174 - 253)
What are the conventions to be followed for the usage of switch case
Below are the list of conventions should be taken care,
- The expression can be of type either number or string.
- Duplicate values are not allowed for the expression.
- The default statement is optional. If the expression passed to switch does not match with any case value then the statement within default case will be executed.
- The break statement is used inside the switch to terminate a statement sequence.
- The break statement is optional. But if it is omitted, the execution will continue on into the next case.
Practical Code Example
javascript
// Best practices for switch-case:
// 1. Always use 'break' or 'return' to prevent accidental fall-through
// 2. Always provide a 'default' fallback
// 3. Use block scoping '{ }' if declaring let/const inside a case
function getHttpStatusDescription(code) {
switch (code) {
case 200:
return 'OK';
case 404: {
const msg = 'Not Found';
return msg;
}
default:
return 'Unknown Status';
}
}