JavaScript switch Statement: Syntax and Examples

JavaScript switch Statement

JavaScript switch statement checks many values without long chains. It appeared to replace stacked conditions that slow you down.

Understand the switch Statement in JavaScript

The switch statement compares one value against many possible matches. It runs the code that matches.

Here is the syntax:

switch (expression) {
  case value1:
    // code block
    break;
  case value2:
    // code block
    break;
  default:
    // code block
}

Here is how it works:

switch (expression):

JavaScript first runs the expression. Then it looks at each case to see if the value matches.

case value1:

If the expression is equal to value1, the code block under this line runs.

break;

This stops the switch. Without break, JavaScript keeps running the next case, even if it does not match. That can lead to bugs if you do not want that. So in most cases, you use break to exit.

default:

This runs only when no case matches. You do not need it, but it helps to handle anything unexpected.

Here is a quick example:

let fruit = "apple";

switch (fruit) {
  case "banana":
    console.log("It is a banana");
    break;
  case "apple":
    console.log("It is an apple");
    break;
  case "orange":
    console.log("It is an orange");
    break;
  default:
    console.log("Fruit not found");
}

The output:

It is an apple

The value of fruit is "apple". JavaScript checks each case until it finds a match. It runs console.log("It is an apple"); when it reaches case "apple": and then stops because of the break.

If you compare ranges or use complex logic, switch is not helpful. Avoid it when values do not match exact cases.

How to Use break in a JavaScript switch Statement

Use break to stop the code from running the next case. Without it, all the next cases run too. You control where the switch block ends. This helps avoid wrong results.

Here is an example:

let grade = "B";
switch (grade) {
  case "A":
    console.log("Excellent");
    break;
  case "B":
    console.log("Good");
    break;
  case "C":
    console.log("Average");
    break;
}

This stops after it matches “B” and prints “Good”. It does not run the other cases.

For another example:

let number = 1;
switch (number) {
  case 1:
    console.log("One");
    break;
  case 2:
    console.log("Two");
    break;
}

It prints “One” and skips the next block. break keeps the output clean. It stops unwanted case execution and gives clear control over the flow.

Use the default Keyword in JavaScript switch Statement

Use default to handle unmatched cases. It acts like a fallback and makes sure your code still runs.

It covers all the missing options and prevents blank or missed outputs.

For example:

let day = "Sunday";
switch (day) {
  case "Monday":
    console.log("Start of the week");
    break;
  default:
    console.log("Not Monday");
}

The day variable is set to “Sunday” and the switch checks for “Monday”, but it doesn’t match. So the default case runs and prints: Not Monday.

Here is another example:

let score = 10;
switch (score) {
  case 100:
    console.log("Perfect");
    break;
  default:
    console.log("Try again");
}

The score is set to 10. It doesn’t match the case 100, so the default runs.
Output: Try again.

The Difference Between switch and if-else

switch checks one value against many fixed values. It works better for simple, direct matches. You read it top to bottom without deep nesting.

The other structure checks many custom conditions. It fits when you check ranges or complex rules. You write flexible checks for each part.

Key Differences

  • switch checks one thing at a time.
  • The other structure lets you compare many things.
  • switch looks cleaner for fixed matches.

For example:

let mood = "happy";
switch (mood) {
  case "happy":
    console.log("Smile");
    break;
  case "sad":
    console.log("Frown");
    break;
}

The mood is "happy", which matches the first case. So it prints: Smile and exits the switch. Output: Smile.

For another example:

let temp = 25;
if (temp > 30) {
  console.log("Hot");
} else {
  console.log("Cool");
}

The temp is 25, which is not greater than 30. So the else block runs. Output: Cool.

Use switch Inside Functions

Use switch inside functions to handle values passed to the function. It keeps the logic in one place. You avoid repeating checks. It also makes testing easier.

For example:

function getSizeLabel(size) {
  switch (size) {
    case "S":
      return "Small";
    case "M":
      return "Medium";
    case "L":
      return "Large";
    default:
      return "Unknown size";
  }
}
console.log(getSizeLabel("M"));

The output:

Medium

The function getSizeLabel("M") checks the size. It matches case "M" and returns "Medium".

Nested switch Statements

You can place one switch inside another. It helps when you sort by two things. Use it when the first match is not enough. It adds depth but needs care.

For example:

let role = "admin";
let action = "edit";
switch (role) {
  case "admin":
    switch (action) {
      case "edit":
        console.log("Admin can edit");
        break;
    }
    break;
}

It prints “Admin can edit” because both conditions match. Here is the output:

Admin can edit

Here is another example:

let user = "guest";
let page = "home";
switch (user) {
  case "guest":
    switch (page) {
      case "home":
        console.log("Guest on home");
        break;
    }
    break;
}

Output:

Guest on home

It prints “Guest on home” by checking both user and page.

Use the switch Statement with Boolean and Expressions in JavaScript

You can pass true or expressions to switch. This helps when your cases do not match a value. Use it when you want to group rules.

For example:

let age = 20;
switch (true) {
  case age < 18:
    console.log("Minor");
    break;
  case age >= 18:
    console.log("Adult");
    break;
}

It prints “Adult” because the age is 20.

Another example:

let score = 75;
switch (true) {
  case score >= 90:
    console.log("A grade");
    break;
  case score >= 70:
    console.log("B grade");
    break;
}

The output:

B grade

It prints a “B grade” because the score is above 70 but below 90.

Type Coercion and Strict Comparison in switch

JavaScript switch uses a loose comparison. It checks values with == instead of ===. That means it converts types to find a match.

For example:

let value = "10";

switch (value) {
  case 10:
    console.log("Matched number");
    break;
  default:
    console.log("No match");
}

This prints Matched. Even though "10" is a string and 10 is an integer, JavaScript treats them as equal.

To avoid issues, make sure case values use the same type as the switch value.

let value = 10;

switch (value) {
  case 10:
    console.log("Exact match");
    break;
}

Or convert the value before switching:

let value = Number("10");

switch (value) {
  case 10:
    console.log("Now it matches");
    break;
}

Type coercion in switch can cause unexpected matches. Always use consistent types or convert values before you compare them.

Using switch(true) with Complex Conditions

Sometimes, you need to check multiple conditions that don’t compare directly to one value. Using switch(true) helps handle this clearly.

Each case tests a condition that returns true or false. The first true case runs.

let score = 75;

switch (true) {
  case score >= 90:
    console.log("A grade");
    break;
  case score >= 70:
    console.log("B grade");
    break;
  case score >= 50:
    console.log("C grade");
    break;
  default:
    console.log("Fail");
}

Here, score >= 70 is true, so it prints “B grade”.

This pattern works like an if-elseif ladder but can be cleaner for multiple ranges.

Examples of JavaScript switch Statement

JavaScript switch Statement Example: Days of the Week:

let day = 3;
switch (day) {
  case 1:
    console.log("Monday");
    break;
  case 3:
    console.log("Wednesday");
    break;
}

The switch checks day against each case using strict matching of value and type. Since day is 3, it matches case 3 and prints “Wednesday.”

Creating a Simple Menu System Using switch:

let option = "view";
switch (option) {
  case "add":
    console.log("Add item");
    break;
  case "view":
    console.log("View item");
    break;
}

The switch compares the string option to each case using strict equality.
It matches "view" and prints “View item”.

How to Handle Multiple Cases with One Block in switch:

let color = "red";
switch (color) {
  case "red":
  case "blue":
    console.log("Primary color");
    break;
}

Both "red" and "blue" cases run the same code because they share it without a break. Since color is "red", it matches the first case and prints “Primary color.”

switch Case with String Values in JavaScript:

let lang = "JavaScript";
switch (lang) {
  case "Python":
    console.log("Python code");
    break;
  case "JavaScript":
    console.log("JS code");
    break;
}

e switch checks if lang matches each case exactly by value and type.
Since lang is "JavaScript", it prints “JS code.”

switch Case with Number Values in JavaScript:

let level = 2;
switch (level) {
  case 1:
    console.log("Low");
    break;
  case 2:
    console.log("Medium");
    break;
}

The switch compares the number level with each case using strict equality.
Since level is 2, it matches case 2 and prints “Medium”.

Wrapping Up

In this article, you learned what the JavaScript switch statement does and how to use it. You also saw how break, default, and nested structures work.

Here is a quick recap:

  • switch checks one value against fixed options.
  • break stops extra cases from running.
  • default handles unmatched values.
  • You can nest or use expressions.

FAQs

What is a switch statement used for in JavaScript?

A switch statement helps you check one value against many possible fixed values. It runs the matching case block and skips the rest. This keeps your code short, readable, and organized when you need to handle multiple options.

When should I avoid switch statements?

Avoid switch when your logic needs to check value ranges or use complex conditions. It works only with strict matches, not comparisons like greater than or less than. For more flexible checks, if-else statements fit better.

Can switch statements replace if-else?

Switch can replace if-else when you compare one fixed value to many fixed cases. But if you need conditions like x > 5 or combine checks, use if-else instead. Switch works best with simple matching, not with flexible logic.

Can I use strings in switch statements?

Yes, JavaScript switch statements can match string values directly. You can compare variables like "apple" or "banana" using string cases. Just make sure your string values match exactly and follow the correct case.

What happens if I forget break?

If you skip the break statement, the code runs all following cases after a match. This is called “fall-through” behavior and often leads to wrong or extra output. Always use break unless you want multiple cases to run on purpose.

Can I nest switch statements?

Yes, you can place one switch block inside another. This helps when you want to match two things like role and action. Be careful though—deep nesting can make your code hard to follow.

Can I use switch in functions?

Yes, switch works well inside functions to handle different input values. It keeps the logic in one place and avoids repeating checks. This makes the function cleaner and easier to test or reuse.

Can switch match expressions?

Yes, switch can match expressions when you pass true as the value. Each case then uses a condition that returns true or false. This works like an if-else chain but stays inside the switch format.

What is default in switch for?

The default case runs when none of the other cases match the value. It acts like a safety net or fallback to handle unexpected inputs. This ensures your switch block always returns some result.
Previous Article

PHP break Statement: How to Exit a Loop

Next Article

PHP htmlspecialchars Function: Prevent XSS in HTML Output

Write a Comment

Leave a Comment

Your email address will not be published. Required fields are marked *

Subscribe to Get Updates

Get the latest updates on Coding, Database, and Algorithms straight to your inbox.
No spam. Unsubscribe anytime.