Mastering the JavaScript switch Statement

Mark O'Neill
Share

The JavaScript switch statement is a way to make decisions in your code based on different conditions. It is a more organized and concise alternative to using multiple if-else statements. The switch statement evaluates a given expression, which can be a variable or a value, and compares it to several possible cases. If the value of the expression matches one of the cases, the associated code block (a set of instructions) is executed. If no match is found, an optional default case can be executed as a fallback, meaning it runs when none of the other cases apply.

For example, here’s a simple switch statement that checks the value of a variable called day:

switch (day) {
  case "Monday":
    console.log("Start of the work week! 😴");
    break;
  case "Friday":
    console.log("End of the work week! 🥳");
    break;
  default:
    console.log("A regular day");
}

By mastering switch statements, you can write cleaner, more efficient, and better-organized JavaScript code, ultimately improving your overall programming skills.

switch Statement Basics: Anatomy and structure

switch statements begins with the keyword switch, followed by an expression in parentheses. This expression is compared to a series of case labels enclosed in a switch block. Each case label represents a distinct value, and the code block that follows the case is executed when the expression matches the case label’s value. A break statement is typically used to exit the switch block after a matching case is executed, ensuring that only the intended code block runs, and preventing fall-through to the next cases. Optionally, a default case can be included to provide a fallback action when none of the case labels match the expression, ensuring a response for unknown values.

switch(expression) {
    case {value1}:
    // <-- Your Code to execute -->  
    break    // optional
    case {value2}:
    // <-- Your Code to execute -->   
    break    // optional
    default: // optional
    // <-- Code that executes when no values match-->
}

const superhero = 'Spider-Man';
switch (superhero) { 
  case 'Batman':
    console.log('🦇 The Dark Knight!');
    break;
  case 'Wonder Woman':
    console.log('👸 The Amazon Princess!');
    break;
  default:
    console.log('💥 There are so many amazing superheroes!');
}

switch vs. if-else

The switch statement is an alternative to using if-else statements when you have multiple conditions to handle. While if-else statements are suitable for checking a series of conditions that can be expressed as true or false, switch statements are more efficient when dealing with a single expression that can take on multiple distinct values. In essence, switch statements can make your code cleaner, more organized, and easier to read when you have several related conditions to manage.

For example, consider the following if-else structure:

if (color === "red") {
  console.log("The color is red 🟥");
} else if (color === "blue") {
  console.log("The color is blue 🟦");
} else if (color === "green") {
  console.log("The color is green 🟩");
} else {
  console.log("Unknown color 🌈");
}

The equivalent switch statement would look like this:

switch (color) {
  case "red":
    console.log("The color is red 🟥");
    break;
  case "blue":
    console.log("The color is blue 🟦");
    break;
  case "green":
    console.log("The color is green 🟩");
    break;
  default:
    console.log("Unknown color 🌈");
}

The switch statement offers a more organized and readable way to handle multiple conditions, particularly when dealing with a large number of cases. In a switch statement, the expression being evaluated is the variable or value inside the parentheses (in this example, the variable color).

When to use switch over if-else

  1. Large number of single-variable conditions: When you have a large number of conditions to handle, switch statements are generally more organized and easier to read than if-else chains.
  2. Single variable evaluation: If the conditions you are evaluating are based on a single variable or expression with multiple distinct values, switch statements can provide a more efficient and cleaner solution than if-else patterns.
  3. Faster code execution: In certain situations, JavaScript engines can optimize switch statements, leading to faster code execution when compared to a series of if-else statements.
  4. Easier maintenance: Switch statements make it easier to add, remove, or modify cases, as each case is self-contained within the switch block. In contrast, if-else chains may require more extensive modifications when changes are needed.
  5. Default fallback: Switch statements provide an optional default case that can be executed when none of the other cases match the given expression. This feature allows for a clean way to handle unexpected or unknown values.

When to use if-else over switch

  1. Complex conditions: If the conditions you are evaluating involve complex logic, multiple variables, or relational and logical operators, if-else patterns provide more flexibility and are better suited for these situations than switch statements.
  2. Range-based conditions: When you need to check for a range of values or conditions that are not discrete, if-else patterns offer a better solution, as switch statements are designed for comparing discrete values.
  3. Small number of conditions: If you have only a few simple conditions to check, using an if-else pattern can be more straightforward and easier to write than a switch statement.
  4. Non-constant cases: Switch statements require constant values for case labels, meaning they cannot be expressions that change at runtime. If you need to evaluate conditions with non-constant values, if-else patterns are the appropriate choice.
  5. Evaluating truthy or falsy values: If-else patterns are suitable when you need to check if a value is truthy or falsy. Switch statements are not designed for this type of evaluation and would require more verbose code to accomplish the same result.
  6. Early exit conditions: If you have an early exit condition where further evaluation is unnecessary once a certain condition is met, if-else patterns can be more efficient. With a switch statement, all cases are evaluated, even if an early match is found (unless you use a “break” statement).

Deciding on switch or if-else

Both switch and if-else solve similar problems and have advantages and disadvantages based on your use cases. To help you make your decision, I’ve created a simple switch statement:

switch (yourUseCase) {
  case 'large_number_of_conditions':
  case 'single_variable_evaluation':
  case 'multiple_discrete_values':
    console.log('Consider using a switch statement.');
    break;
  case 'complex_conditions':
  case 'range_based_conditions':
  case 'non_constant_cases':
    console.log('Consider using an if-else pattern.');
    break;
  default:
    console.log('Choose the most appropriate control structure based on your specific use case.');
}

switch Statement Functionality and Techniques:

The switch statement provides additional functionality and concepts that can be used to improve the performance, readability, and conciseness of your code.

The default case

The default case in a switch statement is executed when none of the other cases match the provided expression. It serves as a fallback to handle unexpected or unknown values, ensuring a response is provided even if there’s no matching case.

const beverage = 'lemonade';

switch (beverage) {
  case 'coffee':
    console.log('☕️ Enjoy your coffee!');
    break;
  case 'tea':
    console.log('🍵 Have a relaxing cup of tea!');
    break;
  default:
    console.log('🥤 Your choice of drink is not listed, but cheers anyway!');
}

The break keyword

The break keyword is used in a switch statement to exit the switch block once a matching case is found and executed. It prevents the code from continuing to execute the remaining cases, ensuring only the correct output is generated.

const transport = 'bike';

switch (transport) {
  case 'car':
    console.log('🚗 Drive safely!');
    break;
  case 'bike':
    console.log('🚲 Enjoy your bike ride!');
    break;
  case 'bus':
    console.log('🚌 Have a pleasant bus journey!');
    break;
}

The Fall-Through technique

A case cannot have more than one condition in a switch statement. To incorporate multiple conditions in one case, consider using the fall-through technique. Not only does it save you time, it ensure you don’t repeat yourself.

Fall-through in a switch statement occurs when you intentionally omit the break keyword in a case, allowing the code execution to continue to the next case(s) until a break is encountered or the end of the switch block is reached. This can be useful when multiple cases share the same output or action.

const clothing = 'jacket';

switch (clothing) {
  case 't-shirt':
  case 'shorts':
    console.log('😎 Looks like it\'s warm outside!');
    break;
  case 'jacket':
  case 'sweater':
    console.log('❄️ Bundle up, it\'s cold!');
    // No break, fall-through to the next case
  case 'scarf':
    console.log('🧣 Don\'t forget your scarf!');
    break;
}

Common issues and pitfalls

Multiple cases executing (Forgetting to use the break statement)

A frequent mistake when using switch statements is not including the break statement after each case. This error results in unintentional fall-through, executing multiple cases instead of just the desired one.

How to fix it: Add a break statement after each case to prevent fall-through.

const mood = 'happy';

switch (mood) {
  case 'happy':
    console.log('😀 Keep smiling!');
    // <--- Missing break statement
  case 'sad':
    console.log('☹️ Cheer up!');
    break;
  case 'angry':
    console.log('😠 Take a deep breath!');
    break;
}

// --Output-- 
//😀 Keep smiling! 
//☹️ Cheer up!

Incorrect Comparison Values and Types

Switch statements use strict comparison, which can lead to unexpected results when comparing different data types. In the example below, the string "2" is not equal to the number 2. This pitfall might cause your cases not to execute as intended.

How to fix: Consider the type of your variables and remember it will be evaluated strictly. TypeScript may help if you’re working on larger projects.

const numOfPets = '2';

switch (numOfPets) {
  case 2: // Because '2' !== 2
    console.log('🐾 Double the fun!');
    break;
  default:
    console.log('🐾 Share the love!');
}

// -- Output --
// 🐾 Share the love!

Scoping issues

A common pitfall in switch statements is declaring variables without block scope or incorrect scopes, causing them to be accessible in other cases, or creating syntax errors. You may experience an Uncaught SyntaxError: ... if you try to redeclare the same variable in multiple clauses.

The fixes:

  • For common variables you intend to use in all cases, declare it with let before your switch statement, or;
  • Scope your clauses as block scope (i.e. wrap your clauses with parentheses { ... })

Block scope your clauses:

// The problem: 
switch (weather) {
  case 'rain':
    const notification = '🌦️ ️Rainy days can be cozy!';
    console.log(notification);
    break;
  case 'thunder':
    // 'notification' is still accessible here
    console.log(notification + ' ⚡ Be careful!');
    break;
}
// Fix 1: Use Block Scope when declaring
switch (weather) {
  case 'rain': { // <-- look here.
    const notification = '🌦️ ️Rainy days can be cozy!';
    console.log(notification);
    break;
  }
  case 'thunder': {
    const notification = '⚡ Be careful!';
    console.log(notification);
    break;
  }
}

// Fix 2: Declare it with let before your statement
let notification = '' // <-- look here.
switch (weather) 
  case 'rain':
    notification = '🌦️ ️Rainy days can be cozy!';
    console.log(notification);
    break;
  case 'thunder':
    notification = '⚡ Be careful!';
    console.log(notification);
    break;
}

Conclusion

Now that you know what a switch statement is, how it works, and when to use it, it’s time to start implementing it! I hope you’ve enjoyed this article. Join us over on the SitePoint Community if you have any questions about this piece or JavaScript in general.