Switch Statements

The switch statement in JavaScript provides a clear, concise way to perform different actions based on multiple possible values of an expression. It is often preferred over multiple if...else if conditions when checking one variable against many values.

Illustration of switch_statements
Illustration of switch_statements

💡 Why Use Switch?

Switch statements improve code readability and organization when handling many discrete cases for the same variable or expression.

Basic Syntax

The structure consists of the switch keyword, an expression to evaluate, and one or more case labels with corresponding code blocks:

📌 Deep Dive: Simple Switch

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
}
  • expression: the value evaluated once.
  • case value: compares expression using strict equality (===).
  • break;: exits the switch to prevent fall-through.
  • default: optional, runs if no case matches.

Important Details

⚠️ Beware of Fall-Through

If you omit break; at the end of a case, execution continues into the next case regardless of the expression value.

This behavior can be useful but often causes bugs if unintentional.

📌 Deep Dive: Fall-Through Behavior

JAVASCRIPT
const fruit = "apple";

switch (fruit) {
  case "apple":
    console.log("Apple selected");
  case "banana":
    console.log("Banana selected");
    break;
  default:
    console.log("No fruit selected");
}
// Output:
// Apple selected
// Banana selected
Output
Apple selected
Banana selected

Using Multiple Cases Together

You can group cases to perform the same action for multiple values by stacking them without breaks:

📌 Deep Dive: Group Cases

JAVASCRIPT
const day = "Saturday";

switch (day) {
  case "Saturday":
  case "Sunday":
    console.log("It's the weekend!");
    break;
  default:
    console.log("It's a weekday.");
}
// Output:
// It's the weekend!
Output
It's the weekend!

Comparison with if...else if

Switch vs if...else if
Switch Statementif...else if
Clear structure for multiple discrete valuesFlexible conditions beyond simple equality
Uses strict equality (===) for matchingCan use any boolean expression
Requires explicit break to prevent fall-throughNo fall-through behavior
Better readability for many discrete casesBetter for complex condition logic

💡 Summary

Use switch when you need to compare one value against many possible constants. Remember to include break; unless intentionally using fall-through.