Falytom logoFALYTOM
Games
ToolsUI ComponentsServicesProductsAbout
LoginSign Up
menu
  1. Home
  2. /Web Development
  3. /Javascript
  4. /Switch Statements
Your Progress0%
0 of 61 completed

JavaScript Topics

Getting Started

  • What is JavaScript?
  • JavaScript vs Other Languages
  • Setting Up Your JavaScript Environment
  • Developer Console and Debugging Basics

JavaScript Fundamentals

  • Variables (var, let, const)
  • Data Types and Type Checking
  • Comments and Code Organization
  • String Methods and Template Literals
  • Type Conversion and Coercion
  • Operators (Arithmetic, Comparison, Logical)

Control Flow

  • If/Else Statements
  • Switch Statements
  • Ternary Operator
  • Truthy and Falsy Values
  • Logical Operators and Short-Circuiting

Loops and Iteration

  • For Loops
  • While and Do-While Loops
  • For...of and For...in Loops
  • Break and Continue Statements

Functions

  • Function Declarations and Expressions
  • Arrow Functions
  • Function Parameters and Arguments
  • Return Statements and Values
  • Scope and Closures
  • Higher-Order Functions and Callbacks

Arrays

  • Array Basics and Creation
  • Array Methods: Adding and Removing Elements
  • Array Iteration Methods (forEach, map, filter)
  • Array Methods: find, some, every, reduce
  • Sorting, Reversing, and Array Transformation

Objects

  • Object Basics and Properties
  • Object Methods and 'this' Keyword
  • Object Destructuring
  • Object.keys, values, entries
  • Spread Operator and Object Cloning

DOM Manipulation

  • Introduction to the DOM
  • Selecting Elements (querySelector, getElementById)
  • Modifying Elements (textContent, innerHTML, style)
  • Creating and Removing Elements
  • Event Listeners and Event Handling
  • Event Object and Event Delegation

Asynchronous JavaScript

  • Understanding Asynchronous Code
  • setTimeout and setInterval
  • Callbacks and Callback Hell
  • Promises and Promise Chaining
  • Async/Await

Error Handling

  • Try, Catch, Finally
  • Throwing Custom Errors

Modern JavaScript Features

  • ES6+ Overview
  • Modules (import/export)
  • Optional Chaining and Nullish Coalescing
  • Rest and Spread Operators

Working with Data

  • JSON (Parse and Stringify)
  • Fetch API and HTTP Requests
  • Working with Local Storage

Advanced Concepts

  • Classes and Object-Oriented Programming
  • Array and Object Advanced Patterns
  • Regular Expressions Basics

Best Practices & Real-World Application

  • JavaScript Best Practices
  • Debugging Techniques and Tools
  • Building a Complete Interactive Project

Switch Statements

Cleaner way to handle multiple conditions

When you need to check a single value against many possible options, switch statements provide a cleaner alternative to long if/else if chains. They're perfect for handling menu selections, status codes, days of the week, and any scenario where you're comparing one value against multiple possibilities. Let's master switch statements!

What Is a Switch Statement?

A switch statement evaluates an expression once and compares it against multiple case values. When a match is found, the corresponding code block executes.

Think of it like a vending machine:

You select one button (the expression). The machine checks which product matches your selection (the cases) and gives you that specific product (executes that code).

Basic Syntax

JAVASCRIPT
switch (expression) {
  case value1:
    // Code to execute if expression === value1
    break;
  case value2:
    // Code to execute if expression === value2
    break;
  case value3:
    // Code to execute if expression === value3
    break;
  default:
    // Code to execute if no case matches
    break;
}

Basic Switch Statement

Simple Example

JAVASCRIPT
let day = "Monday";

switch (day) {
  case "Monday":
    console.log("Start of work week");
    break;
  case "Tuesday":
    console.log("Second day");
    break;
  case "Wednesday":
    console.log("Midweek");
    break;
  case "Thursday":
    console.log("Almost Friday");
    break;
  case "Friday":
    console.log("Last work day!");
    break;
  case "Saturday":
  case "Sunday":
    console.log("Weekend!");
    break;
  default:
    console.log("Not a valid day");
    break;
}
// Output: "Start of work week"

How It Works

  1. JavaScript evaluates the expression in switch(expression)
  2. It compares the result with each case value using strict equality (===)
  3. When a match is found, the code after that case executes
  4. The break statement exits the switch
  5. If no case matches, the default case executes (if present)

The Break Statement

The break statement is crucial in switch statements. It exits the switch block, preventing "fall-through" to the next case.

With Break (Normal Behavior)

JAVASCRIPT
let grade = "B";

switch (grade) {
  case "A":
    console.log("Excellent!");
    break;  // Exits switch here
  case "B":
    console.log("Good job!");
    break;  // Exits switch here
  case "C":
    console.log("Passed");
    break;
  default:
    console.log("Need improvement");
    break;
}
// Output: "Good job!"

Without Break (Fall-Through)

JAVASCRIPT
let grade = "B";

switch (grade) {
  case "A":
    console.log("Excellent!");
    // No break! Falls through to next case
  case "B":
    console.log("Good job!");
    // No break! Falls through to next case
  case "C":
    console.log("Passed");
    break;
  default:
    console.log("Need improvement");
    break;
}
// Output:
// "Good job!"
// "Passed"

// If grade was "A", output would be:
// "Excellent!"
// "Good job!"
// "Passed"

Important: Forgetting break causes fall-through, where execution continues into the next case. This is usually a bug, but can be intentional for grouping cases.

The Default Case

The default case is optional but recommended. It executes when no other case matches—like the else in an if/else statement.

JAVASCRIPT
let color = "purple";

switch (color) {
  case "red":
    console.log("Stop");
    break;
  case "yellow":
    console.log("Caution");
    break;
  case "green":
    console.log("Go");
    break;
  default:
    console.log("Unknown color");
    break;
}
// Output: "Unknown color"

// Without default
switch (color) {
  case "red":
    console.log("Stop");
    break;
  case "yellow":
    console.log("Caution");
    break;
  case "green":
    console.log("Go");
    break;
  // No default - nothing happens if no match
}
// No output

Default Placement

JAVASCRIPT
// Default typically goes at the end (convention)
switch (value) {
  case 1:
    console.log("One");
    break;
  case 2:
    console.log("Two");
    break;
  default:
    console.log("Other");
    break;
}

// But can be anywhere (works the same)
switch (value) {
  default:
    console.log("Other");
    break;
  case 1:
    console.log("One");
    break;
  case 2:
    console.log("Two");
    break;
}

// Convention: Put default at the end for readability

💡 Best Practice:

Always include a default case, even if it just logs an error or does nothing. This makes your code more robust and helps catch unexpected values during development.

Multiple Cases for Same Action

You can group multiple case values that should execute the same code by stacking them without breaks.

JAVASCRIPT
// Weekend checker
let day = "Saturday";

switch (day) {
  case "Monday":
  case "Tuesday":
  case "Wednesday":
  case "Thursday":
  case "Friday":
    console.log("Workday");
    break;
  case "Saturday":
  case "Sunday":
    console.log("Weekend!");
    break;
  default:
    console.log("Invalid day");
    break;
}
// Output: "Weekend!"

// Season checker
let month = "March";

switch (month) {
  case "December":
  case "January":
  case "February":
    console.log("Winter");
    break;
  case "March":
  case "April":
  case "May":
    console.log("Spring");
    break;
  case "June":
  case "July":
  case "August":
    console.log("Summer");
    break;
  case "September":
  case "October":
  case "November":
    console.log("Fall");
    break;
  default:
    console.log("Invalid month");
    break;
}
// Output: "Spring"

Practical Example: Vowel Checker

JAVASCRIPT
function isVowel(letter) {
  letter = letter.toLowerCase();
  
  switch (letter) {
    case "a":
    case "e":
    case "i":
    case "o":
    case "u":
      return true;
    default:
      return false;
  }
}

console.log(isVowel("A"));  // true
console.log(isVowel("e"));  // true
console.log(isVowel("b"));  // false
console.log(isVowel("Z"));  // false

Switch vs If/Else

When should you use switch instead of if/else? Here's a comparison.

Same logic, different syntax

If/Else Chain

// Using if/else
let status = "success";

if (status === "success") {
  console.log("Operation successful");
} else if (status === "error") {
  console.log("An error occurred");
} else if (status === "warning") {
  console.log("Warning message");
} else if (status === "info") {
  console.log("Information");
} else {
  console.log("Unknown status");
}
Output:
Not run yet...

Switch Statement

// Using switch
let status = "success";

switch (status) {
  case "success":
    console.log("Operation successful");
    break;
  case "error":
    console.log("An error occurred");
    break;
  case "warning":
    console.log("Warning message");
    break;
  case "info":
    console.log("Information");
    break;
  default:
    console.log("Unknown status");
    break;
}
Output:
Not run yet...

When to Use Switch

Use switch when:

  • Comparing one variable against many specific values
  • Values are discrete (strings, numbers, not ranges)
  • You have 3+ possible values to check
  • You want cleaner, more readable code for many cases
  • Cases might need to fall through to each other

When to Use If/Else

Use if/else when:

  • Checking different variables or complex conditions
  • Using comparison operators (>, <, >=, <=)
  • Checking ranges (age >= 18 && age < 65)
  • Combining multiple conditions with && or ||
  • Conditions are more complex than simple equality
JAVASCRIPT
// GOOD use of switch: checking discrete values
switch (userRole) {
  case "admin":
    grantFullAccess();
    break;
  case "editor":
    grantEditAccess();
    break;
  case "viewer":
    grantViewAccess();
    break;
}

// BAD use of switch: ranges require if/else
let age = 25;
switch (true) {  // Anti-pattern!
  case age < 13:
    console.log("Child");
    break;
  case age < 20:
    console.log("Teen");
    break;
  // This is confusing - use if/else instead
}

// GOOD: Use if/else for ranges
if (age < 13) {
  console.log("Child");
} else if (age < 20) {
  console.log("Teen");
} else if (age < 65) {
  console.log("Adult");
} else {
  console.log("Senior");
}

Using Return in Switch

Inside functions, you can use return instead of break. This exits both the switch and the function.

JAVASCRIPT
// With break
function getDayType(day) {
  let type;
  
  switch (day) {
    case "Monday":
    case "Tuesday":
    case "Wednesday":
    case "Thursday":
    case "Friday":
      type = "Weekday";
      break;
    case "Saturday":
    case "Sunday":
      type = "Weekend";
      break;
    default:
      type = "Invalid";
      break;
  }
  
  return type;
}

// With return (cleaner)
function getDayTypeBetter(day) {
  switch (day) {
    case "Monday":
    case "Tuesday":
    case "Wednesday":
    case "Thursday":
    case "Friday":
      return "Weekday";
    case "Saturday":
    case "Sunday":
      return "Weekend";
    default:
      return "Invalid";
  }
}

console.log(getDayTypeBetter("Monday"));  // "Weekday"
console.log(getDayTypeBetter("Sunday"));  // "Weekend"

Note: When using return, you don't need break because the function exits immediately. This makes the code cleaner and easier to read.

Switch Uses Strict Equality

Switch statements use strict equality (===), meaning both value and type must match. This is important to remember!

JAVASCRIPT
let value = "5";  // String

switch (value) {
  case 5:  // Number 5
    console.log("Number five");
    break;
  case "5":  // String "5"
    console.log("String five");  // This executes!
    break;
}
// Output: "String five"

// Type matters!
let num = 5;

switch (num) {
  case "5":
    console.log("This won't execute");
    break;
  case 5:
    console.log("This will execute");  // This one!
    break;
}

// If you need loose equality, convert first
let input = "5";
switch (Number(input)) {
  case 5:
    console.log("Now it matches!");  // Executes
    break;
}

Practical Examples

Example 1: Calculator

JAVASCRIPT
function calculate(num1, num2, operator) {
  switch (operator) {
    case "+":
      return num1 + num2;
    case "-":
      return num1 - num2;
    case "*":
      return num1 * num2;
    case "/":
      if (num2 === 0) {
        return "Cannot divide by zero";
      }
      return num1 / num2;
    case "%":
      return num1 % num2;
    case "**":
      return num1 ** num2;
    default:
      return "Invalid operator";
  }
}

console.log(calculate(10, 5, "+"));   // 15
console.log(calculate(10, 5, "*"));   // 50
console.log(calculate(10, 0, "/"));   // "Cannot divide by zero"
console.log(calculate(10, 5, "^"));   // "Invalid operator"

Example 2: HTTP Status Handler

JAVASCRIPT
function handleHTTPStatus(statusCode) {
  switch (statusCode) {
    case 200:
    case 201:
    case 204:
      return { success: true, message: "Success" };
    
    case 400:
      return { success: false, message: "Bad Request" };
    
    case 401:
      return { success: false, message: "Unauthorized" };
    
    case 403:
      return { success: false, message: "Forbidden" };
    
    case 404:
      return { success: false, message: "Not Found" };
    
    case 500:
    case 502:
    case 503:
      return { success: false, message: "Server Error" };
    
    default:
      return { success: false, message: "Unknown Status" };
  }
}

console.log(handleHTTPStatus(200));
// { success: true, message: "Success" }

console.log(handleHTTPStatus(404));
// { success: false, message: "Not Found" }

console.log(handleHTTPStatus(500));
// { success: false, message: "Server Error" }

Example 3: Menu System

JAVASCRIPT
function processMenuChoice(choice) {
  switch (choice) {
    case "1":
    case "new":
      return startNewGame();
    
    case "2":
    case "load":
      return loadGame();
    
    case "3":
    case "settings":
      return openSettings();
    
    case "4":
    case "help":
      return showHelp();
    
    case "5":
    case "quit":
    case "exit":
      return quitGame();
    
    default:
      return "Invalid choice. Please try again.";
  }
}

function startNewGame() {
  return "Starting new game...";
}

function loadGame() {
  return "Loading saved game...";
}

function openSettings() {
  return "Opening settings...";
}

function showHelp() {
  return "Showing help menu...";
}

function quitGame() {
  return "Goodbye!";
}

console.log(processMenuChoice("1"));      // "Starting new game..."
console.log(processMenuChoice("new"));    // "Starting new game..."
console.log(processMenuChoice("quit"));   // "Goodbye!"
console.log(processMenuChoice("99"));     // "Invalid choice..."

Example 4: Grade Letter to GPA

JAVASCRIPT
function gradeToGPA(grade) {
  // Normalize to uppercase
  grade = grade.toUpperCase();
  
  switch (grade) {
    case "A+":
    case "A":
      return 4.0;
    
    case "A-":
      return 3.7;
    
    case "B+":
      return 3.3;
    
    case "B":
      return 3.0;
    
    case "B-":
      return 2.7;
    
    case "C+":
      return 2.3;
    
    case "C":
      return 2.0;
    
    case "C-":
      return 1.7;
    
    case "D+":
      return 1.3;
    
    case "D":
      return 1.0;
    
    case "F":
      return 0.0;
    
    default:
      return null;
  }
}

console.log(gradeToGPA("A"));   // 4.0
console.log(gradeToGPA("B+"));  // 3.3
console.log(gradeToGPA("c"));   // 2.0 (normalized to uppercase)
console.log(gradeToGPA("Z"));   // null

Switch Statement Practice

Experiment with different switch patterns

Output:
Click "Run" to execute your code...
💡 Tip: Use console.log() to see your output in the console above.

Common Mistakes

1. Forgetting Break

JAVASCRIPT
// WRONG: Forgot break
let grade = "B";

switch (grade) {
  case "A":
    console.log("Excellent!");
  case "B":
    console.log("Good!");  // Executes
  case "C":
    console.log("OK");     // Also executes! (fall-through)
    break;
}
// Output: "Good!" and "OK"

// RIGHT: Add break
switch (grade) {
  case "A":
    console.log("Excellent!");
    break;
  case "B":
    console.log("Good!");
    break;  // Stops here
  case "C":
    console.log("OK");
    break;
}
// Output: "Good!" only

2. Type Mismatch

JAVASCRIPT
// WRONG: String vs Number
let input = "5";  // String from user input

switch (input) {
  case 5:  // Number
    console.log("Five");  // Won't execute!
    break;
}

// RIGHT: Convert or match type
switch (Number(input)) {
  case 5:
    console.log("Five");  // Now it works!
    break;
}

// Or match the string
switch (input) {
  case "5":
    console.log("Five");  // Works!
    break;
}

3. Forgetting Default

JAVASCRIPT
// RISKY: No default case
let status = "unknown";

switch (status) {
  case "success":
    console.log("Success");
    break;
  case "error":
    console.log("Error");
    break;
  // No default - unexpected values do nothing
}
// No output - fails silently!

// BETTER: Add default
switch (status) {
  case "success":
    console.log("Success");
    break;
  case "error":
    console.log("Error");
    break;
  default:
    console.log("Unknown status:", status);  // Catches unexpected values
    break;
}

Key Takeaways

  • Switch statements compare one value against multiple cases
  • Use break to exit after each case (prevents fall-through)
  • The default case handles unmatched values
  • Switch uses strict equality (===) for comparisons
  • Stack cases without breaks to handle multiple values the same way
  • Use return instead of break inside functions
  • Switch is cleaner than if/else for checking discrete values
  • Use if/else for ranges and complex conditions
  • Always include default case for unexpected values
  • Watch out for type mismatches (string vs number)

What's Next?

You now know how to use switch statements to handle multiple conditions cleanly! Switch statements are particularly useful for handling user selections, status codes, and any scenario where you're checking one value against many options.

In the next lesson, we'll revisit the Ternary Operatorin more depth—a concise way to write simple if/else statements in a single line. Perfect for quick conditional assignments and inline conditions!

💪 Practice Challenge:

Before moving on, try creating:

  1. A function that converts number grades (1-7) to letter grades (A-F)
  2. A command processor that handles different user commands (help, start, stop, etc.)
  3. A currency converter that handles multiple currency codes (USD, EUR, GBP, etc.)
  4. A game controller that processes different button presses (up, down, left, right, A, B)
  5. A status message generator for different HTTP status codes

Test Your Understanding

Question 1 / 4

What does the 'break' statement do in a switch?

Score: 0 / 0

Learning JavaScript switch statements! 🔀

Previous
If/Else Statements
Next
Ternary Operator

Continue Learning JavaScript

Join 2,000+ developers mastering JavaScript control flow. New lessons weekly - 100% FREE.

You might also like

UI Components

Ready-made components for your projects

Developer Tools

Boost productivity with handy generators

HTML Game

Learn HTML concepts through interactive gameplay

Join Our Web Development Training Program

Master frontend & backend development with hands-on projects.

JavaScript Tutorials

0 of 61 completed

Your Progress0%

Topics

Getting Started

  • What is JavaScript?
  • JavaScript vs Other Languages
  • Setting Up Your JavaScript Environment
  • Developer Console and Debugging Basics

JavaScript Fundamentals

  • Variables (var, let, const)
  • Data Types and Type Checking
  • Comments and Code Organization
  • String Methods and Template Literals
  • Type Conversion and Coercion
  • Operators (Arithmetic, Comparison, Logical)

Control Flow

  • If/Else Statements
  • Switch Statements
  • Ternary Operator
  • Truthy and Falsy Values
  • Logical Operators and Short-Circuiting

Loops and Iteration

  • For Loops
  • While and Do-While Loops
  • For...of and For...in Loops
  • Break and Continue Statements

Functions

  • Function Declarations and Expressions
  • Arrow Functions
  • Function Parameters and Arguments
  • Return Statements and Values
  • Scope and Closures
  • Higher-Order Functions and Callbacks

Arrays

  • Array Basics and Creation
  • Array Methods: Adding and Removing Elements
  • Array Iteration Methods (forEach, map, filter)
  • Array Methods: find, some, every, reduce
  • Sorting, Reversing, and Array Transformation

Objects

  • Object Basics and Properties
  • Object Methods and 'this' Keyword
  • Object Destructuring
  • Object.keys, values, entries
  • Spread Operator and Object Cloning

DOM Manipulation

  • Introduction to the DOM
  • Selecting Elements (querySelector, getElementById)
  • Modifying Elements (textContent, innerHTML, style)
  • Creating and Removing Elements
  • Event Listeners and Event Handling
  • Event Object and Event Delegation

Asynchronous JavaScript

  • Understanding Asynchronous Code
  • setTimeout and setInterval
  • Callbacks and Callback Hell
  • Promises and Promise Chaining
  • Async/Await

Error Handling

  • Try, Catch, Finally
  • Throwing Custom Errors

Modern JavaScript Features

  • ES6+ Overview
  • Modules (import/export)
  • Optional Chaining and Nullish Coalescing
  • Rest and Spread Operators

Working with Data

  • JSON (Parse and Stringify)
  • Fetch API and HTTP Requests
  • Working with Local Storage

Advanced Concepts

  • Classes and Object-Oriented Programming
  • Array and Object Advanced Patterns
  • Regular Expressions Basics

Best Practices & Real-World Application

  • JavaScript Best Practices
  • Debugging Techniques and Tools
  • Building a Complete Interactive Project
Falytom logoFALYTOM

Learn technologies like HTML, CSS, JavaScript, React, NodeJS and more through interactive games, tutorials, components and free tools. Transform your businesses with AI chatbots, SEO-optimized websites, and professional development services.

© 2025 Tomilola Group
  • Facebook logo
  • Twitter logo
  • Instagram logo
  • LinkedIn logo
  • GitHub logo
  • YouTube logo