InterviewHubPRO
Section Overview
Q227

Question 227 of 521

Part 4: Prototypes, Object Methods & Event Loop (174 - 253)

44%
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,

  1. The expression can be of type either number or string.
  2. Duplicate values are not allowed for the expression.
  3. 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.
  4. The break statement is used inside the switch to terminate a statement sequence.
  5. 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';
  }
}