Back to Web Development
2026-01-037 min read

Switch (Web Development)

Learn Switch (Web Development) step by step with clear examples and exercises.

Why This Matters

In web development, especially in JavaScript, the switch statement is an essential tool for simplifying code and handling multiple conditions. It helps developers write cleaner, more efficient code, making it a valuable asset in any developer's toolkit. By using the switch statement, you can reduce complexity and make your code easier to maintain and understand.

Prerequisites

To fully grasp this lesson, you should be familiar with:

  1. Basic HTML syntax and structure
  2. CSS for styling web pages
  3. JavaScript fundamentals, including variables, functions, loops, conditional statements (if-else), and basic DOM manipulation
  4. Understanding the concept of objects and arrays in JavaScript
  5. Familiarity with browser developer tools to debug your code and understand its behavior

Core Concept

The switch statement in JavaScript is used to evaluate an expression against multiple cases. It works by comparing the value of the expression with each case, starting from the first one. If a match is found, the code within that case block is executed. Here's a basic structure:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Switch Example</title>
</head>
<body>
<script>
// Define the variable to be evaluated
let fruit = "apple";

// Use the switch statement to evaluate the fruit
switch (fruit) {
case "apple":
console.log("The fruit is an apple.");
break;
case "banana":
console.log("The fruit is a banana.");
break;
// Add more cases as needed
default:
console.log("Unknown fruit.");
}
</script>
</body>
</html>

In this example, the fruit variable is evaluated against each case in the switch statement. If the value of fruit matches "apple", the corresponding code block is executed, and the script ends with the break statement to prevent further execution within the switch block.

Note on Strings

When comparing strings, remember that they are case-sensitive and should be enclosed in quotes (e.g., "apple").

Using switch with objects

You can also use the switch statement with JavaScript objects to evaluate properties of an object. Here's an example:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Switch Example with Object</title>
</head>
<body>
<script>
// Define the object to be evaluated
let animal = {
cat: "Meow",
dog: "Woof",
bird: "Chirp"
};

// Use the switch statement to evaluate the animal's sound
switch (animal.cat) {
case animal.cat:
console.log("The animal makes a cat sound: ", animal.cat);
break;
case animal.dog:
console.log("The animal makes a dog sound: ", animal.dog);
break;
case animal.bird:
console.log("The animal makes a bird sound: ", animal.bird);
break;
default:
console.log("Unknown animal.");
}
</script>
</body>
</html>

In this example, we use the switch statement with an object to evaluate the property of the animal object and display the corresponding sound.

Using switch with arrays

You can also use the switch statement with JavaScript arrays to evaluate array elements. Here's an example:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Switch Example with Array</title>
</head>
<body>
<script>
// Define the array to be evaluated
let colors = ["red", "blue", "green"];

// Use the switch statement to evaluate the color array
switch (colors[1]) {
case colors[0]:
console.log("The second color is the first color.");
break;
case colors[1]:
console.log("The second color is the second color.");
break;
case colors[2]:
console.log("The second color is the third color.");
break;
default:
console.log("The second color is not in the array.");
}
</script>
</body>
</html>

In this example, we use the switch statement with an array to evaluate the second element of the colors array and compare it with other elements in the array.

Worked Example

Let's create a simple web page that allows users to input their age and displays an appropriate message based on their age group using the switch statement.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Age Group Determiner</title>
<style>
.result { color: blue; font-weight: bold; }
</style>
</head>
<body>
<h1>Determine Your Age Group</h1>
<label for="age">Enter your age:</label>
<input type="number" id="age" name="age">
<button onclick="determineAgeGroup()">Submit</button>
<p class="result"></p>

<script>
function determineAgeGroup() {
// Get the user's age from the input field
let age = document.getElementById("age").value;

// Use the switch statement to determine the age group
switch (true) {
case age < 13:
resultText = "You are a child.";
break;
case age <= 19:
resultText = "You are a teenager.";
break;
case age <= 24:
resultText = "You are a young adult.";
break;
case age <= 64:
resultText = "You are an adult.";
break;
case age >= 65 && age <= 80:
resultText = "You are a senior citizen (65-80).";
break;
default:
resultText = "You are a senior citizen (above 80).";
}

// Display the result in the paragraph element
document.getElementsByClassName("result")[0].innerText = resultText;
}
</script>
</body>
</html>

In this example, we use a switch statement with multiple cases to determine the age group of the user based on their input. The expression inside the parentheses is always true, so the switch evaluates each case as if it were an "if" statement. If the condition for a case is met, the corresponding code block is executed, and the script ends with the break statement to prevent further execution within the switch block.

Common Mistakes

  1. Forgetting the break statement: This can cause unexpected behavior as the code within subsequent cases will be executed even if a match has already been found.
  2. Not providing a default case: If no matches are found, the script will not execute any code within the switch block. Adding a default case ensures that some output is displayed in this situation.
  3. Using the == operator instead of ===: In JavaScript, using the loose equality operator (==) can lead to unexpected matches due to type coercion. It's recommended to use the strict equality operator (===) for better results.
  4. Not properly handling strings: When comparing strings, remember that they are case-sensitive and should be enclosed in quotes.
  5. Using switch with complex expressions: While it is possible to use complex expressions within a switch statement, it can make the code harder to read and maintain. It's recommended to break down complex expressions into separate variables before using them in the switch statement.
  6. Not handling null or undefined values: If you are evaluating a variable that may be null or undefined, remember to handle these cases separately to avoid errors.

Practice Questions

  1. Write a switch statement that evaluates the value of a variable color and displays a message based on its value (e.g., "The color is red.").
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Color Determiner</title>
</head>
<body>
<script>
// Define the variable to be evaluated
let color = "red";

// Use the switch statement to evaluate the color
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.");
}
</script>
</body>
</html>
  1. Modify the age group determiner example to include an additional age group for users between 65 and 80 years old.
  1. Write a switch statement that evaluates a variable grade representing a student's grade (e.g., "A", "B", "C", etc.) and displays a message based on the grade (e.g., "Excellent work!" for an "A" grade).
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Grade Determiner</title>
</head>
<body>
<script>
// Define the variable to be evaluated
let grade = "A";

// Use the switch statement to evaluate the grade
switch (grade) {
case "A":
console.log("Excellent work!");
break;
case "B":
console.log("Good job!");
break;
case "C":
console.log("Keep trying!");
break;
default:
console.log("Please enter a valid grade.");
}
</script>
</body>
</html>
  1. Write a switch statement that evaluates the day of the week based on an input value (e.g., "Monday", "Tuesday", etc.) and displays a message about the day.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Day of the Week Determiner</title>
</head>
<body>
<script>
// Define the variable to be evaluated
let day = "Monday";

// Use the switch statement to evaluate the day
switch (day) {
case "Monday":
console.log("Today is Monday.");
break;
case "Tuesday":
console.log("Today is Tuesday.");
break;
case "Wednesday":
console.log("Today is Wednesday.");
break;
case "Thursday":
console.log("Today is Thursday.");
break;
case "Friday":
console.log("Today is Friday.");
break;
case "Saturday":
console.log("Today is Saturday.");
break;
case "Sunday":
console.log("Today is Sunday.");
break;
default:
console.log("Please enter a valid day of the week.");
}
</script>
</body>
</html>

FAQ

What happens if I don't include a break statement in my switch block?

Without a break statement, the code within subsequent cases will be executed even if a match has already been found, causing unexpected behavior.

Can I use complex expressions inside a switch statement?

Yes, it is possible to use complex expressions within a switch statement, but it can make the code harder to read and maintain. It's recommended to break down complex expressions into separate variables before using them in the switch statement.

Why do I need to enclose strings in quotes when using a switch statement?

Strings are case-sensitive in JavaScript, so enclosing them in quotes ensures that they are treated as strings and compared correctly.

What should I do if my evaluated variable may be null or undefined?

If you are evaluating a variable that may be null or undefined, it's recommended to handle these cases separately to avoid errors. You can add a default case for null or undefined values, or check for

Switch (Web Development) | Web Development | XQA Learn