JavaScript Basics

JavaScript Switch Statement: Complete Guide with Examples

Master the JavaScript switch statement for cleaner conditional logic. Learn syntax, fall-through behavior, and when to use switch vs if-else.

By JavaScript Document Team
switchconditionalscontrol-flowbasicsstatements

The switch statement provides a cleaner way to handle multiple conditional branches compared to lengthy if-else chains. This guide covers everything you need to know about using switch statements effectively in JavaScript.

Basic Switch Syntax

The switch statement evaluates an expression and executes code based on matching cases.

Simple Switch Statement

const day = 3;

switch (day) {
  case 1:
    console.log('Monday');
    break;
  case 2:
    console.log('Tuesday');
    break;
  case 3:
    console.log('Wednesday');
    break;
  case 4:
    console.log('Thursday');
    break;
  case 5:
    console.log('Friday');
    break;
  case 6:
    console.log('Saturday');
    break;
  case 7:
    console.log('Sunday');
    break;
  default:
    console.log('Invalid day');
}
// Output: Wednesday

Switch with Strings

const fruit = 'apple';

switch (fruit) {
  case 'apple':
    console.log('Apples are $0.99/lb');
    break;
  case 'banana':
    console.log('Bananas are $0.59/lb');
    break;
  case 'orange':
    console.log('Oranges are $0.79/lb');
    break;
  case 'mango':
    console.log('Mangoes are $1.99/lb');
    break;
  default:
    console.log('Sorry, we are out of ' + fruit);
}

Switch with Expressions

const score = 85;

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;
  case score >= 60:
    console.log('Grade: D');
    break;
  default:
    console.log('Grade: F');
}
// Output: Grade: B

The break Statement

The break statement is crucial in switch cases to prevent fall-through behavior.

With break

const color = 'red';

switch (color) {
  case 'red':
    console.log('Color is red');
    break;
  case 'blue':
    console.log('Color is blue');
    break;
  case 'green':
    console.log('Color is green');
    break;
}
// Output: Color is red

Without break (Fall-through)

const number = 2;

switch (number) {
  case 1:
    console.log('One');
  // No break - falls through
  case 2:
    console.log('Two');
  // No break - falls through
  case 3:
    console.log('Three');
    break;
  case 4:
    console.log('Four');
    break;
}
// Output: Two
//         Three

Intentional Fall-through

const month = 'January';
let season;

switch (month) {
  case 'December':
  case 'January':
  case 'February':
    season = 'Winter';
    break;
  case 'March':
  case 'April':
  case 'May':
    season = 'Spring';
    break;
  case 'June':
  case 'July':
  case 'August':
    season = 'Summer';
    break;
  case 'September':
  case 'October':
  case 'November':
    season = 'Fall';
    break;
  default:
    season = 'Unknown';
}

console.log(`${month} is in ${season}`);
// Output: January is in Winter

The default Case

The default case executes when no other cases match.

default Placement

// default at the end (common)
const pet = 'hamster';

switch (pet) {
  case 'dog':
    console.log('Dogs are loyal');
    break;
  case 'cat':
    console.log('Cats are independent');
    break;
  default:
    console.log('Unknown pet type');
}

// default in the middle (less common but valid)
const browser = 'Safari';

switch (browser) {
  case 'Chrome':
    console.log('Google Chrome');
    break;
  default:
    console.log('Other browser');
    break;
  case 'Firefox':
    console.log('Mozilla Firefox');
    break;
}
// Output: Other browser

Multiple defaults (Only First Executes)

const value = 'test';

switch (value) {
  case 'a':
    console.log('A');
    break;
  default:
    console.log('First default');
    break;
  default:
    console.log('Second default'); // Never executes
    break;
}
// Output: First default

Complex Switch Patterns

Grouping Cases

const action = 'UPDATE';

switch (action) {
  case 'CREATE':
  case 'UPDATE':
  case 'PATCH':
    console.log('Modifying data...');
    handleModification();
    break;

  case 'DELETE':
  case 'REMOVE':
    console.log('Removing data...');
    handleDeletion();
    break;

  case 'GET':
  case 'FETCH':
  case 'READ':
    console.log('Reading data...');
    handleRetrieval();
    break;

  default:
    console.log('Unknown action');
}

function handleModification() {
  console.log('Data modified');
}

function handleDeletion() {
  console.log('Data deleted');
}

function handleRetrieval() {
  console.log('Data retrieved');
}

Switch with Return

function getDayName(dayNumber) {
  switch (dayNumber) {
    case 0:
      return 'Sunday';
    case 1:
      return 'Monday';
    case 2:
      return 'Tuesday';
    case 3:
      return 'Wednesday';
    case 4:
      return 'Thursday';
    case 5:
      return 'Friday';
    case 6:
      return 'Saturday';
    default:
      return 'Invalid day';
  }
  // No break needed after return
}

console.log(getDayName(3)); // Wednesday
console.log(getDayName(7)); // Invalid day

Nested Switch

const category = 'fruit';
const item = 'apple';

switch (category) {
  case 'fruit':
    switch (item) {
      case 'apple':
        console.log('Apple: A healthy fruit');
        break;
      case 'banana':
        console.log('Banana: High in potassium');
        break;
      default:
        console.log('Unknown fruit');
    }
    break;

  case 'vegetable':
    switch (item) {
      case 'carrot':
        console.log('Carrot: Good for eyes');
        break;
      case 'spinach':
        console.log('Spinach: Rich in iron');
        break;
      default:
        console.log('Unknown vegetable');
    }
    break;

  default:
    console.log('Unknown category');
}

Type Comparison in Switch

Switch uses strict comparison (===) for matching cases.

Strict Comparison

const value = '10';

switch (value) {
  case 10:
    console.log('Number 10');
    break;
  case '10':
    console.log('String "10"');
    break;
}
// Output: String "10"

// Type coercion doesn't happen
const input = '2';

switch (input) {
  case 2:
    console.log('Will not match');
    break;
  case '2':
    console.log('This matches');
    break;
}

Comparing Objects

const obj1 = { name: 'John' };
const obj2 = { name: 'John' };
const obj3 = obj1;

switch (obj1) {
  case obj2:
    console.log('obj1 === obj2');
    break;
  case obj3:
    console.log('obj1 === obj3');
    break;
  default:
    console.log('No match');
}
// Output: obj1 === obj3 (reference equality)

Switch vs If-Else

When to Use Switch

// Good use case: Multiple specific values
const status = 'pending';

switch (status) {
  case 'pending':
    handlePending();
    break;
  case 'approved':
    handleApproved();
    break;
  case 'rejected':
    handleRejected();
    break;
  case 'cancelled':
    handleCancelled();
    break;
  default:
    handleUnknown();
}

// Alternative with if-else (more verbose)
if (status === 'pending') {
  handlePending();
} else if (status === 'approved') {
  handleApproved();
} else if (status === 'rejected') {
  handleRejected();
} else if (status === 'cancelled') {
  handleCancelled();
} else {
  handleUnknown();
}

When to Use If-Else

// Complex conditions: Use if-else
const age = 25;
const hasLicense = true;
const hasInsurance = true;

if (age >= 18 && hasLicense && hasInsurance) {
  console.log('Can rent a car');
} else if (age >= 18 && hasLicense) {
  console.log('Need insurance to rent');
} else if (age >= 18) {
  console.log('Need license and insurance');
} else {
  console.log('Too young to rent');
}

// Range checking: Better with if-else
const temperature = 75;

if (temperature < 32) {
  console.log('Freezing');
} else if (temperature < 60) {
  console.log('Cold');
} else if (temperature < 80) {
  console.log('Comfortable');
} else {
  console.log('Hot');
}

Practical Examples

Menu System

function handleMenuChoice(choice) {
  switch (choice.toLowerCase()) {
    case '1':
    case 'new':
    case 'n':
      console.log('Creating new document...');
      createNewDocument();
      break;

    case '2':
    case 'open':
    case 'o':
      console.log('Opening document...');
      openDocument();
      break;

    case '3':
    case 'save':
    case 's':
      console.log('Saving document...');
      saveDocument();
      break;

    case '4':
    case 'exit':
    case 'quit':
    case 'q':
      console.log('Exiting...');
      exitApplication();
      break;

    default:
      console.log('Invalid choice. Please try again.');
  }
}

// Usage
handleMenuChoice('1'); // Creating new document...
handleMenuChoice('save'); // Saving document...
handleMenuChoice('q'); // Exiting...

State Machine

class TrafficLight {
  constructor() {
    this.state = 'red';
  }

  transition() {
    switch (this.state) {
      case 'red':
        this.state = 'green';
        console.log('🟢 Green - Go!');
        break;

      case 'green':
        this.state = 'yellow';
        console.log('🟡 Yellow - Caution!');
        break;

      case 'yellow':
        this.state = 'red';
        console.log('🔴 Red - Stop!');
        break;

      default:
        console.error('Invalid state');
        this.state = 'red';
    }
  }
}

const light = new TrafficLight();
light.transition(); // 🟢 Green - Go!
light.transition(); // 🟡 Yellow - Caution!
light.transition(); // 🔴 Red - Stop!

HTTP Status Handler

function handleHTTPStatus(status) {
  const statusCode = Math.floor(status / 100);

  switch (statusCode) {
    case 2:
      console.log(`✅ Success: ${status}`);
      switch (status) {
        case 200:
          console.log('OK');
          break;
        case 201:
          console.log('Created');
          break;
        case 204:
          console.log('No Content');
          break;
      }
      break;

    case 3:
      console.log(`↪️ Redirection: ${status}`);
      break;

    case 4:
      console.log(`❌ Client Error: ${status}`);
      switch (status) {
        case 400:
          console.log('Bad Request');
          break;
        case 401:
          console.log('Unauthorized');
          break;
        case 404:
          console.log('Not Found');
          break;
      }
      break;

    case 5:
      console.log(`💥 Server Error: ${status}`);
      break;

    default:
      console.log(`❓ Unknown status: ${status}`);
  }
}

handleHTTPStatus(200); // ✅ Success: 200, OK
handleHTTPStatus(404); // ❌ Client Error: 404, Not Found
handleHTTPStatus(500); // 💥 Server Error: 500

Calculator Function

function calculate(num1, num2, operator) {
  let result;

  switch (operator) {
    case '+':
    case 'add':
      result = num1 + num2;
      break;

    case '-':
    case 'subtract':
      result = num1 - num2;
      break;

    case '*':
    case 'multiply':
      result = num1 * num2;
      break;

    case '/':
    case 'divide':
      if (num2 === 0) {
        return 'Error: Division by zero';
      }
      result = num1 / num2;
      break;

    case '%':
    case 'modulo':
      result = num1 % num2;
      break;

    case '**':
    case 'power':
      result = num1 ** num2;
      break;

    default:
      return 'Error: Invalid operator';
  }

  return `${num1} ${operator} ${num2} = ${result}`;
}

console.log(calculate(10, 5, '+')); // 10 + 5 = 15
console.log(calculate(10, 5, 'subtract')); // 10 subtract 5 = 5
console.log(calculate(10, 0, '/')); // Error: Division by zero

Alternative Patterns

Object Lookup

// Instead of switch, use object mapping
const dayNames = {
  1: 'Monday',
  2: 'Tuesday',
  3: 'Wednesday',
  4: 'Thursday',
  5: 'Friday',
  6: 'Saturday',
  7: 'Sunday',
};

function getDayName(day) {
  return dayNames[day] || 'Invalid day';
}

// Function mapping
const operations = {
  add: (a, b) => a + b,
  subtract: (a, b) => a - b,
  multiply: (a, b) => a * b,
  divide: (a, b) => a / b,
};

function calculate(op, a, b) {
  return operations[op] ? operations[op](a, b) : 'Invalid operation';
}

Map for Complex Logic

const handlers = new Map([
  ['create', () => console.log('Creating...')],
  ['read', () => console.log('Reading...')],
  ['update', () => console.log('Updating...')],
  ['delete', () => console.log('Deleting...')],
]);

function handleAction(action) {
  const handler = handlers.get(action.toLowerCase());
  if (handler) {
    handler();
  } else {
    console.log('Unknown action');
  }
}

Common Pitfalls

Missing break

// Bug: Missing break causes fall-through
const grade = 'B';

switch (grade) {
  case 'A':
    console.log('Excellent!');
  // Missing break!
  case 'B':
    console.log('Good job!');
  // Missing break!
  case 'C':
    console.log('You passed');
    break;
}
// Output: Good job!
//         You passed  (unintended)

Variable Declaration in Cases

const action = 'create';

switch (action) {
  case 'create':
    // Use block scope for variable declarations
    {
      const message = 'Creating item';
      console.log(message);
    }
    break;

  case 'delete':
    {
      const message = 'Deleting item'; // No conflict
      console.log(message);
    }
    break;
}

Best Practices

  1. Always use break unless fall-through is intentional
  2. Include a default case for unexpected values
  3. Use object maps for simple value mapping
  4. Consider if-else for complex conditions
  5. Group related cases for better readability
  6. Use block scope for case-specific variables
  7. Keep cases simple - extract complex logic to functions

Conclusion

The switch statement is a powerful tool for handling multiple conditional branches based on a single expression. While it's not always the best choice for every situation, it can make your code more readable and maintainable when dealing with multiple discrete values. Understanding when to use switch versus if-else statements, and being aware of fall-through behavior, will help you write cleaner and more efficient JavaScript code.