Academic Block

JavaScript Switch Get Certified

The switch statement is an alternative to writing long chains of if...else if statements. It compares one value against several possible cases and runs the matching block of code.

A switch statement is often easier to read than a long if...else if chain when you are checking the same value against many possible options.

In this lesson, you will learn the syntax of switch, how break and fall-through behave, and when to prefer switch over if...else.

Basic switch Syntax

A switch statement evaluates an expression once and compares its value against each case using strict equality (===).

What this code does: A switch compares one value against several cases. Because day is Tuesday, that case runs and prints its message, then break stops further checks.

let day = "Tuesday";
switch (day) {
    case "Monday":
        console.log("Start of the work week.");
        break;
    case "Tuesday":
        console.log("Second day of the week.");
        break;
    default:
        console.log("Some other day.");
}

The break Keyword

The break statement stops the switch from continuing to check the remaining cases. Without it, execution “falls through” into the next case.

What this code does: Each case is checked with strict equality. fruit is banana, so that case’s message is printed. break prevents fall-through to later cases.

let fruit = "banana";
switch (fruit) {
    case "apple":
        console.log("Apples are red or green.");
        break;
    case "banana":
        console.log("Bananas are yellow.");
        break;
    case "grape":
        console.log("Grapes are small and round.");
        break;
    default:
        console.log("Unknown fruit.");
}

Fall-Through Behavior

If you forget break, JavaScript continues executing the code in the next case, even if its condition doesn’t match. This is called “fall-through.”

What this code does: Without break, execution “falls through” into the next cases. Matching banana also runs the grape and default messages. Always use break unless fall-through is intentional.

let fruit = "banana";
switch (fruit) {
    case "apple":
        console.log("Apples are red or green.");
    case "banana":
        console.log("Bananas are yellow.");
    case "grape":
        console.log("Grapes are small and round.");
    default:
        console.log("Unknown fruit.");
}

Notice that once "banana" matches, every case after it also runs because there is no break to stop execution.

Intentional Fall-Through

Fall-through isn’t always a mistake. It can be used intentionally to group multiple cases that should run the same code.

What this code does: Multiple cases can share the same code by stacking them (intentional fall-through). Saturday and Sunday both print the weekend message; weekdays share the other message.

let day = "Saturday";
switch (day) {
    case "Saturday":
    case "Sunday":
        console.log("It's the weekend!");
        break;
    case "Monday":
    case "Tuesday":
    case "Wednesday":
    case "Thursday":
    case "Friday":
        console.log("It's a weekday.");
        break;
    default:
        console.log("Not a valid day.");
}

Here, "Saturday" and "Sunday" share the same code block by having no statements (and no break) between their case labels.

The default Case

The default case runs when none of the other cases match. It is optional, but it’s good practice to include one to handle unexpected values.

What this code does: switch works with numbers too. Status code 404 matches its case and prints “Not Found”. The default handles any unmatched value.

let statusCode = 404;
switch (statusCode) {
    case 200:
        console.log("OK");
        break;
    case 404:
        console.log("Not Found");
        break;
    case 500:
        console.log("Server Error");
        break;
    default:
        console.log("Unknown status code");
}

The default case does not have to be the last one in the switch block, but placing it last is the most common and readable convention.

switch Uses Strict Comparison

A switch statement compares values using strict equality (===), meaning both the value and the type must match.

What this code does: switch uses strict equality (===). The string "5" does not match the number 5, so the string case runs instead.

let value = "5";
switch (value) {
    case 5:
        console.log("Matched the number 5");
        break;
    case "5":
        console.log("Matched the string \"5\"");
        break;
    default:
        console.log("No match");
}

Even though 5 == "5" is true, switch only matches the string case here, since it compares using === rather than ==.

Using Expressions in case Labels

By using switch (true), you can evaluate a boolean condition in each case, which allows range checks similar to an if...else if chain.

What this code does: switch (true) can test ranges, similar to else if. Each case is a condition; the first one that is true wins. Score 82 gives grade B.

let score = 82;
switch (true) {
    case (score >= 90):
        console.log("Grade: A");
        break;
    case (score >= 80):
        console.log("Grade: B");
        break;
    case (score >= 70):
        console.log("Grade: C");
        break;
    default:
        console.log("Grade: F");
}

switch vs. if…else

Aspect if…else switch
Best for Complex or range-based conditions Comparing one value against many exact options
Comparison type Any expression Strict equality (===) by default
Readability with many options Can get long and repetitive Often clearer and more organized
Grouping multiple values Requires && / || Fall-through between case labels

Practical Example

Let’s use a switch statement to handle a simple menu selection.

What this code does: A function can use switch to return different values. getMenuPrice("coffee") returns 3.5. Using return exits the function, so break is not required.

function getMenuPrice(item) {
    switch (item) {
        case "coffee":
            return 3.5;
        case "tea":
            return 2.5;
        case "sandwich":
            return 6.0;
        default:
            return 0;
    }
}
console.log("Coffee price:", getMenuPrice("coffee"));
console.log("Tea price:", getMenuPrice("tea"));
console.log("Unknown item price:", getMenuPrice("soup"));

Notice that return inside a case immediately exits the function, which is why break is unnecessary after a return statement.

Common Mistakes With switch

  • Forgetting break, causing unintended fall-through into the next case.
  • Expecting switch to use loose equality (==) like some other comparisons in JavaScript.
  • Omitting the default case, so unexpected values are silently ignored.
  • Declaring variables with let or const directly inside a case without wrapping it in a block, which can cause scope-related errors.
  • Using switch for complex range checks when a regular if...else if chain would be clearer.

Declaring Variables Inside a case

Since all case labels share the same block scope, declaring a variable with the same name in multiple cases can cause a SyntaxError. Wrapping each case in curly braces creates its own block scope.

What this code does: When you declare variables inside a case, wrap the body in curly braces to create a block scope. That avoids conflicts if the same variable name is used in another case.

let action = "add";
let result;
switch (action) {
    case "add": {
        const message = "Adding items";
        result = message;
        break;
    }
    case "remove": {
        const message = "Removing items";
        result = message;
        break;
    }
    default: {
        result = "Unknown action";
    }
}
console.log(result);

Best Practices for switch

  • Always include a break at the end of each case, unless fall-through is intentional.
  • Always include a default case to handle unexpected values.
  • Wrap each case body in curly braces when declaring variables inside it.
  • Use switch when comparing one value against many specific options; use if...else for more complex or range-based logic.
  • Add a short comment when using intentional fall-through, so future readers know it wasn’t a mistake.

Quick Summary

  • switch compares one expression against several case values using strict equality.
  • break stops execution from falling into the next case.
  • Fall-through happens automatically without break, and can be used intentionally to group cases.
  • default runs when no other case matches.
  • switch (true) can be used for range-based conditions similar to if...else if.
  • Use curly braces around a case body when declaring block-scoped variables inside it.

Try It Yourself

Modify the value below. Try changing day to "Sunday", or to a day not listed, and observe how the output changes.

What this code does: Practice example: change day to Sunday or another value, then click Test My Code to see the weekend vs weekday message.

let day = "Wednesday";
switch (day) {
    case "Saturday":
    case "Sunday":
        console.log("It's the weekend!");
        break;
    default:
        console.log("It's a weekday.");
}
Tip: If you find yourself writing if (x === a) ... else if (x === b) ... else if (x === c), that’s usually a strong sign a switch statement would express the same logic more clearly.

Understanding switch is useful before moving on to loops, functions, and more advanced JavaScript concepts.

🧪 Test Your JavaScript Code

Edit the code on the left and click “Run Code” to see the console output on the right.

📝 JavaScript Code
👁 Console Output

Click “Run Code” to see the output here.

Ctrl + Enter to run code Esc to close