Switch statements

Topic 3 of 5 in Operators & control flow6 min readBeginnerFree course

Overview

When you compare one value against many possibilities, switch can be easier to read than a long else if chain.

JavaScript
const status = 'paused';

switch (status) {
  case 'playing':
    console.log('Now playing');
    break;
  case 'paused':
    console.log('Paused');
    break;
  default:
    console.log('Stopped');
}

Compare it with the equivalent if chain, which repeats status === on every line:

JavaScript
if (status === 'playing') {
  console.log('Now playing');
} else if (status === 'paused') {
  console.log('Paused');
} else {
  console.log('Stopped');
}

How switch works

  1. JavaScript evaluates the expression in switch ( … ) once.
  2. It compares the result with each case value using ===, from top to bottom.
  3. At the first match, it starts running code from that case.
  4. It keeps running — through any following cases — until it reaches a break, a return, or the end of the switch.
  5. If nothing matches, it runs the default block (if there is one).

Because the comparison is strict, types must match:

JavaScript
switch ('1') {
  case 1:
    console.log('number one'); // not reached — '1' !== 1
    break;
  case '1':
    console.log('string one'); // runs
    break;
}

Fall-through

Each case runs until it reaches break or return. This is called fall-through. Leaving break out on purpose lets several cases share code:

With fruit = ‘lemon’: case ‘apple’ doesn’t match and is skipped; case ‘lemon’ matches so execution starts there; it has no break, so it falls through into case ‘lime’, prints Sour!, and break exits; default is skipped.

JavaScript
switch (fruit) {
  case 'lemon':
  case 'lime':
    console.log('Sour!');
    break;
  default:
    console.log('Tasty.');
}

Forgetting break is a classic bug — the next case runs too. Inside a function, using return in each case avoids it.

Here’s what the bug looks like:

JavaScript
const level = 'gold';
switch (level) {
  case 'gold':
    console.log('Free shipping');
  case 'silver':
    console.log('10% off');
  default:
    console.log('Thanks for shopping');
}
// Free shipping, 10% off, Thanks for shopping — all three!

If you ever do want fall-through between cases that have code, leave a comment such as // falls through so readers know it’s deliberate.

Returning from cases

Inside a function, return both produces a value and leaves the switch (and the function), so you don’t need break:

JavaScript
function shippingCost(zone) {
  switch (zone) {
    case 'local':
      return 0;
    case 'national':
      return 49;
    case 'international':
      return 499;
    default:
      throw new Error(`Unknown zone: ${zone}`);
  }
}

Throwing an error in default is a good habit when every valid value should be covered — a typo such as 'nationl' fails loudly instead of silently doing the wrong thing.

Variables inside cases

All the cases share one block, so declaring the same const name in two cases is an error. Wrap a case’s code in its own braces to give it a private scope:

JavaScript
switch (shape) {
  case 'circle': {
    const area = Math.PI * r ** 2;
    console.log(area);
    break;
  }
  case 'square': {
    const area = side ** 2; // fine — a separate block
    console.log(area);
    break;
  }
}

Matching ranges with switch (true)

switch only checks equality, so it can’t directly test ranges like “score above 90”. A trick you’ll sometimes see is switch (true), where each case is a condition:

JavaScript
switch (true) {
  case score >= 90:
    grade = 'A';
    break;
  case score >= 75:
    grade = 'B';
    break;
  default:
    grade = 'C';
}

It works, but most developers find an if…else if chain clearer for ranges.

An object lookup instead

If each case just produces a value, a plain object is often shorter:

JavaScript
const icons = { playing: '▶', paused: '⏸', stopped: '⏹' };
const icon = icons[status] ?? '?';

The object acts as a table: keys on the left, results on the right. The ?? provides a fallback, like default. Lookups can hold functions, too:

JavaScript
const handlers = {
  save: () => saveDocument(),
  open: () => openDialog(),
  quit: () => closeApp(),
};

handlers[command]?.();

Which should I use?

Situation Best choice
Two or three outcomes if…else
Ranges (> 90, < 0) if…else if
One value against many fixed values, each running some code switch
One value mapped straight to another value Object lookup (or a Map)
Exercise

Day type

Use switch to return 'weekend' for 'Sat' and 'Sun', 'midweek' for 'Wed', and 'weekday' for everything else.

JavaScript
function dayType(day) {
  // your code here
}

Summary

  • switch compares one value with === against each case, from top to bottom.
  • Without break (or return), execution falls through to the next case.
  • Stacking empty cases lets several values share the same code.
  • default runs when nothing matches — always include one.
  • For simple value-to-value mapping, an object lookup is often clearer.