JavaScript Switch Statement

The switch statement in JavaScript is used to perform different actions based on different conditions, often making the code cleaner than using multiple if-else statements.

It's commonly used when comparing a single value against multiple possibilities.



What You'll Learn

You'll learn how the switch statement works, its syntax, when to use it, and how it compares to if-else chains.


Understanding the switch Statement

Here’s the basic syntax:

javascript
switch (expression) {
  case value1:
    // Code block
    break;
  case value2:
    // Code block
    break;
  default:
    // Default block
}
  • expression: A value or variable to compare against each case.
  • case: Each condition to compare. If matched, runs the associated block.
  • break: Stops the execution of the switch block. Without it, execution "falls through" to the next case.
  • default: Runs if no case matches. Optional but useful.

Example 1: Basic Switch Statement

This example demonstrates how to use the switch statement to check the day of the week. Based on the value, it prints a corresponding message.

javascript
let day = "Monday";

switch (day) {
    case "Monday":
        console.log("Start of the week!");
        break;
    case "Tuesday":
        console.log("Second day of the week.");
        break;
    case "Wednesday":
        console.log("Mid-week!");
        break;
    case "Thursday":
        console.log("Almost the weekend.");
        break;
    case "Friday":
        console.log("Last workday!");
        break;
    default:
        console.log("It's the weekend!");
}

How It Works:

  • day = "Monday": We set the day to "Monday".
  • switch(day): We begin the switch statement, checking the value of the day variable.
  • case "Monday": The first case checks if day is "Monday".
  • If true, it prints "Start of the week!" to the console and breaks out of the switch.
  • The break statement ensures the switch block stops once a case is matched.

Output

Start of the week!

Example 2: Using Switch to Check Even or Odd

This example uses a switch statement to check if a number is even or odd using the modulo operator %.

javascript
let number = 5;

switch (number % 2 === 0) {
    case true:
        console.log("The number is even.");
        break;
    case false:
        console.log("The number is odd.");
        break;
    default:
        console.log("Invalid number.");
}

How It Works:

  • number = 5: We set the value of the number to 5.
  • switch (number % 2 === 0): The switch checks if the number is even by using the modulo operator.
  • case true:: If the condition is true (i.e., the number is even), it prints "The number is even." to the console.
  • case false:: If the condition is false (i.e., the number is odd), it prints "The number is odd.".
  • The break statement exits the switch block after a match is found.

Output

The number is odd.

Example 3: Using Switch to Compare Multiple Values

This example demonstrates how to use the switch statement to compare multiple values and execute corresponding blocks of code.

javascript
let fruit = "apple";

switch (fruit) {
    case "apple":
        console.log("This is an apple.");
        break;
    case "banana":
        console.log("This is a banana.");
        break;
    case "orange":
        console.log("This is an orange.");
        break;
    default:
        console.log("Unknown fruit.");
}

How It Works:

  • fruit = "apple": We set the variable fruit to "apple".
  • switch(fruit): The switch statement checks the value of the fruit variable.
  • case "apple":: This case matches if the value of fruit is "apple".
  • If true, it prints "This is an apple." to the console and exits the switch block using break.
  • If no case matches, the default case is executed, printing "Unknown fruit.".

Output

This is an apple.

Exercises

Try these to test your understanding of the switch statement:

1. Print the season based on a month number (1–12).
javascript
let month = 4;

switch (month) {
  case 12:
  case 1:
  case 2:
    console.log("Winter");
    break;
  case 3:
  case 4:
  case 5:
    console.log("Spring");
    break;
  case 6:
  case 7:
  case 8:
    console.log("Summer");
    break;
  case 9:
  case 10:
  case 11:
    console.log("Fall");
    break;
  default:
    console.log("Invalid month");
}

2. Check meal time: "breakfast", "lunch", or "dinner".
javascript
let time = "lunch";

switch (time) {
  case "breakfast":
    console.log("Good morning!");
    break;
  case "lunch":
    console.log("Good afternoon!");
    break;
  case "dinner":
    console.log("Good evening!");
    break;
  default:
    console.log("Time not recognized.");
}

*Tip: Modify variable values to test different outcomes!


Frequently Asked Questions

What is a switch statement in JavaScript?

A switch statement allows you to check a variable against multiple possible values and execute the corresponding block of code. It's an alternative to using multiple if-else statements for cleaner code.


How does a switch statement differ from if-else?

A switch statement is ideal for comparing one variable to multiple constant values. It's more readable and efficient when there are many cases to check, whereas if-else is better for complex expressions or ranges.


Can you use a switch statement with ranges or conditions other than equality?

No, switch statements in JavaScript only compare the variable to constant values for equality. For ranges or more complex conditions, you should use if-else.


Is it possible to have multiple case labels in a switch statement?

Yes, you can group multiple case labels together. If multiple values should execute the same code, they can share a single block of code by falling through to the next case.


Can a switch statement be used with non-numeric values?

Yes, switch statements can be used with strings, numbers, or any expression that evaluates to a value, as long as the case values are of the same type.



What's Next?

Next, you'll dive into functions in JavaScript, which are reusable blocks of code designed to perform specific tasks. You'll learn how to define and call functions, pass arguments, return values, and understand the different types of functions, including function declarations, expressions, and arrow functions.