0
0
JavascriptHow-ToBeginner · 3 min read

How to Use Switch Case in JavaScript: Syntax and Examples

In JavaScript, use the switch statement to execute different code blocks based on a variable's value. It compares the variable to multiple case values and runs the matching block until a break is found or the switch ends. Use default to handle unmatched cases.
📐

Syntax

The switch statement evaluates an expression and matches it against multiple case values. Each case has code to run if it matches. The break keyword stops the switch from running the next cases. The default case runs if no other case matches.

javascript
switch (expression) {
  case value1:
    // code to run if expression === value1
    break;
  case value2:
    // code to run if expression === value2
    break;
  default:
    // code to run if no case matches
    break;
}
💻

Example

This example shows how to use switch to print a message based on a day of the week.

javascript
const day = 'Tuesday';
switch (day) {
  case 'Monday':
    console.log('Start of the work week');
    break;
  case 'Tuesday':
    console.log('Second day of the work week');
    break;
  case 'Friday':
    console.log('Last work day!');
    break;
  default:
    console.log('Midweek days');
    break;
}
Output
Second day of the work week
⚠️

Common Pitfalls

One common mistake is forgetting break statements, which causes "fall-through" where multiple cases run unintentionally. Another is not handling the default case, which can leave some values unhandled. Also, switch uses strict equality (===), so types must match exactly.

javascript
const fruit = 'apple';
switch (fruit) {
  case 'apple':
    console.log('Apple selected');
  case 'banana':
    console.log('Banana selected');
    break;
  default:
    console.log('Unknown fruit');
}

// Corrected version with breaks:
switch (fruit) {
  case 'apple':
    console.log('Apple selected');
    break;
  case 'banana':
    console.log('Banana selected');
    break;
  default:
    console.log('Unknown fruit');
    break;
}
Output
Apple selected Banana selected
📊

Quick Reference

  • switch(expression): The value to compare.
  • case value: Runs if expression === value.
  • break: Stops running more cases.
  • default: Runs if no case matches.
  • Use strict equality (===) for matching.

Key Takeaways

Use switch to run code based on matching values of an expression.
Always include break to prevent unintended fall-through between cases.
Use default to handle unmatched cases safely.
Switch uses strict equality (===), so types must match exactly.
Switch is cleaner than many if-else statements when checking multiple values.