Lesson 21: Mastering JavaScript Switch statements with challenges!

manoj ymkmanoj ymk
6 min read

The switch statement is a control structure used to handle multiple conditions in a concise manner. It is typically used when you have one variable and want to compare it against several possible values (cases). It is more readable than multiple if-else statements when you have many conditions to check.

Syntax:

switch(expression) {
  case value1:
    // Code block
    break;
  case value2:
    // Code block
    break;
  case value3:
    // Code block
    break;
  default:
    // Code block if no match
}
  • Expression: The value being checked.

  • Cases: Each case is checked against the expression.

  • Break: Stops execution once a match is found.

  • Default: Optionally, handles cases when no match is found.

Example:

let a = 2 + 2; // a is 4

switch (a) {
  case 3:
    console.log('Too small');
    break;
  case 4:
    console.log('Exactly!');
    break;
  case 5:
    console.log('Too big');
    break;
  default:
    console.log("I don't know such values");
}

Output: 'Exactly!' (because a === 4 matches case 4).


🔹 2. Fill Any Gaps

  • Strict Equality: switch uses strict equality (===), so the values must match in both type and value. This means that a string '5' won't match the number 5.

  • Fall-through: If a break is omitted, execution falls through to the next case, potentially leading to unintended behavior.

    Example of Fall-through:

      let a = 2;
      switch(a) {
        case 2:
          console.log('two');
        case 3:
          console.log('three');
        default:
          console.log('default');
      }
    

    Output:

      two
      three
      default
    
  • Expressions: Both switch and case can accept expressions, not just constants. You can evaluate complex conditions or use expressions.

    Example:

      let a = "1";
      let b = 0;
      switch(+a) {
        case b + 1:
          console.log("Matched!");
          break;
        default:
          console.log("Not matched");
      }
    

    Here, +a is 1 and b + 1 is also 1, so the case matches.

  • Grouping Cases: Multiple case labels can be grouped to run the same code without repeating it.

    Example:

      let a = 3;
      switch(a) {
        case 3:
        case 5:
          console.log('Wrong!');
          break;
        default:
          console.log('default');
      }
    

    This will log 'Wrong!' because 3 and 5 are grouped together.

  • Type Matters: A common mistake is not considering the type of the value being compared. For example, '3' (string) is not equal to 3 (number).

    Example:

      let value = '3';
      switch (value) {
        case 3:
          console.log('Matched!');
          break;
        default:
          console.log('No match');
      }
    

    Output: 'No match' because '3' (string) is not the same as 3 (number).


🔹 3. Challenge Me Deeply

🟢 Basic Challenges

  1. Write a switch statement to check if a number is positive, negative, or zero.

  2. Write a switch statement that checks the day of the week (e.g., 1 for Monday) and outputs the name of the day.

🟡 Intermediate Challenges

  1. Create a switch statement to match a string and print a different message based on whether it's "apple", "banana", or something else.

  2. Modify a switch statement to execute different logic for multiple case values that should run the same code (e.g., handle "apple" and "orange" the same way).

  3. Use a switch statement to convert a number from 1 to 4 into a grade: 1 = 'A', 2 = 'B', 3 = 'C', and 4 = 'F'.

🔴 Advanced Challenges

  1. Create a switch statement that checks the type of a variable (string, number, object, etc.) and logs an appropriate message for each type.

  2. Write a switch statement that evaluates a mathematical expression based on a user's input (e.g., +, -, *, /) and performs the operation.

  3. Write a switch that finds whether a given date is in the past, present, or future based on today's date.

🧠 Brain Twister

  1. In a switch statement, there’s a known fall-through bug where a break was mistakenly omitted. How would you debug and correct the code without modifying the switch structure too much?

  2. Write a switch statement that outputs different messages depending on the input value. The value should be parsed from an external API response (simulating it with a mock value). How would you handle unexpected or missing values robustly?


🔹 4. Interview-Ready Questions

Concept-Based

  1. What is the difference between a switch statement and multiple if-else statements in JavaScript?

  2. Can you explain the concept of fall-through behavior in switch statements? When might it be useful?

Scenario-Based

  1. If a switch statement is used with a large number of cases, what performance considerations should be kept in mind?

  2. How do you handle situations where a switch statement is expected to process both numbers and strings?

Debugging-Style

  1. You have a switch statement with multiple cases. The code works for all cases except one. How would you debug the issue?

  2. What would happen if you accidentally omit a break in the middle of a switch block? How can you prevent such errors?

Best Practices and Red Flags

  • Best Practice: Always use break unless you intend to use fall-through.

  • Red Flag: Using switch when the conditions involve more complex logic or range comparisons (use if-else instead).


🔹 5. Real-World Usage

switch statements are useful in modern development when:

  • Routing and Navigation: In routing libraries (like React Router), a switch statement is used to select the correct route based on the URL.

  • State Machine: In applications with a set of predefined states (e.g., UI workflows), switch can be used to switch between states.

  • Menu Systems: In apps with complex menus, switch can be used to handle various menu options.

Example in React (Routing):

import { Switch, Route } from 'react-router-dom';

function App() {
  return (
    <Switch>
      <Route path="/home" component={Home} />
      <Route path="/about" component={About} />
      <Route component={NotFound} />
    </Switch>
  );
}

🔹 6. Remember Like a Pro

Mnemonic: Think of a switch as a "selector". It picks the correct action based on the value you give it. Imagine a vending machine where you press a button (the switch expression) and it gives you the corresponding snack (the case).


🔹 7. Apply It in a Fun Way

Mini Project: Create a Calculator

  1. Step 1: Create a simple switch calculator that evaluates simple math expressions (+, -, *, /).

  2. Step 2: Accept two numbers from the user and a mathematical operator.

  3. Step 3: Use a switch statement to execute the corresponding operation.

let num1 = prompt("Enter first number:");
let num2 = prompt("Enter second number:");
let operator = prompt("Enter operator (+, -, *, /):");

switch(operator) {
  case '+':
    console.log(num1 + num2);
    break;
  case '-':
    console.log(num1 - num2);
    break;
  case '*':
    console.log(num1 * num2);
    break;
  case '/':
    console.log(num1 / num2);
    break;
  default:
    console.log("Invalid operator");
}

Bonus Extension:

  • Allow the user to handle multiple operations in one go (e.g., chaining operations).

  • Add error handling for non-numeric input.


🔹 8. Extra Value

Open-Source Projects

  • React Router: A switch statement is often used to match URL paths with the corresponding components.

  • Redux: A switch statement may be used to handle various actions in reducers.

Common Mistakes

  • Forgetting the break statement leads to unintended fall-through.

  • Using switch for complex conditions that would be better handled by if-else (e.g., range checking).

Performance Tips

  • When dealing with a large number of cases, consider using object mapping instead of switch for improved performance.

Polyfills

  • In some legacy browsers (e.g., IE6), switch behavior is consistent, but fallback logic might be needed for edge cases like missing break statements.
0
Subscribe to my newsletter

Read articles from manoj ymk directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

manoj ymk
manoj ymk