Coding

JavaScript Switch Case: Syntax, Break and Examples

A JavaScript switch statement evaluates one expression, jumps to the first case whose value is strictly equal (===) to it, and runs from there until a break or the end of the block. If no case matches, it runs default.

const day = "tue";

switch (day) {
  case "mon":
    console.log("Start of the week");
    break;
  case "tue":
    console.log("Second day");
    break;
  default:
    console.log("Some other day");
}
// Logs: Second day

JavaScript switch case syntax

The general shape, as documented on MDN:

switch (expression) {
  case value1:
    statements
    break;
  case value2:
    statements
    break;
  default:
    statements
}

The expression in the parentheses is evaluated once. Each case value is then compared against the result, in order, from top to bottom. Once one matches, the later case expressions are not evaluated at all. MDN shows this with case console.log(1): case console.log(2): on a value that matches the first: only 1 is logged.

Switch compares with strict equality

Matching uses ===, so there is no type coercion. This catches people who read form input or query strings, where numbers arrive as text:

const quantity = "1"; // a string, for example from an input field

switch (quantity) {
  case 1:
    console.log("number one");
    break;
  case "1":
    console.log("string one");
    break;
}
// Logs: string one

If your value might be the wrong type, convert it first, for example switch (Number(quantity)). For a fuller explanation of what strict equality does and does not convert, see == vs === in JavaScript.

One consequence of ===: NaN is never strictly equal to anything, including itself, so no case can match a NaN value. It always reaches default.

What break does, and what happens without it

break leaves the switch. Without it, execution falls through into the next clause, whether or not that clause's value matches. MDN's example:

const foo = 0;
switch (foo) {
  case -1:
    console.log("negative 1");
    break;
  case 0: // match starts here
    console.log(0);
  // Forgotten break! Execution falls through
  case 1:
    console.log(1);
    break; // stops here
  case 2:
    console.log(2);
    break;
  default:
    console.log("default");
}
// Logs 0, then 1

Two other statements also leave a switch. Inside a function, return ends the whole function, which is a common way to write a lookup without any break:

function dayName(number) {
  switch (number) {
    case 0: return "Sunday";
    case 1: return "Monday";
    case 2: return "Tuesday";
    default: return "Unknown";
  }
}

Inside a loop, continue jumps to the next iteration of the loop. Accidental fall-through is the most common switch bug, which is why linters flag it. ESLint, for instance, has a separate no-fallthrough rule for it.

How to run the same code for several cases

Stack the case labels with nothing between them. Fall-through then does the work on purpose. This is the one place where leaving out break is normal:

const animal = "Giraffe";
switch (animal) {
  case "Cow":
  case "Giraffe":
  case "Dog":
  case "Pig":
    console.log("This animal is not extinct.");
    break;
  case "Dinosaur":
  default:
    console.log("This animal is extinct.");
}
// Logs: This animal is not extinct.

This example is from MDN. Note that case "Dinosaur": also stacks onto default, so both lead to the same message.

How default works

default runs when no case matches. Three rules to know:

  • You can have only one. A second default clause is a SyntaxError.
  • It can sit anywhere in the block, though putting it last is the convention.
  • If it is not last and has no break, execution continues into the clauses below it.

MDN's example of the last rule:

const foo = 5;
switch (foo) {
  case 2:
    console.log(2);
    break;
  default:
    console.log("default");
  // fall-through
  case 1:
    console.log("1");
}
// Logs "default", then "1"

A switch with no default simply does nothing when nothing matches. That is fine for optional handling, but for input you expect to be one of a fixed set of values, a default that throws an error makes bad input visible instead of silent.

Why "Identifier has already been declared" appears in a switch

A case clause does not create its own scope. The whole switch body is one block, so two const or let declarations with the same name in different cases collide:

switch (action) {
  case "say_hello":
    const message = "hello";
    console.log(message);
    break;
  case "say_hi":
    const message = "hi"; // error
    console.log(message);
    break;
}
// Uncaught SyntaxError: Identifier 'message' has already been declared

The fix is to wrap each clause that declares something in braces, which gives each one its own block:

switch (action) {
  case "say_hello": {
    const message = "hello";
    console.log(message);
    break;
  }
  case "say_hi": {
    const message = "hi";
    console.log(message);
    break;
  }
}

Even with different names, ESLint's no-case-declarations rule warns about let, const, function and class declared directly in a clause. Its documentation explains the reason: the declaration is visible in the entire switch block but is only initialized when its own case runs, so another case can reach the name before it has a value. Braces around the clause fix that too.

Using switch (true) for conditions

Because every case is compared with ===, you can switch on the value true and write a boolean expression in each case. The first expression that evaluates to exactly true wins:

function describe(score) {
  switch (true) {
    case score >= 90:
      return "A";
    case score >= 80:
      return "B";
    case score >= 70:
      return "C";
    default:
      return "Below C";
  }
}

describe(85); // "B"

MDN documents this pattern as an alternative to an if...else chain. It has a catch that follows from strict equality: a case expression that returns something truthy but not true, such as a non-empty string or the number 5, will not match. Keep each case a real comparison or a function that returns a boolean. For plain ranges, an if...else if chain reads just as well and avoids the surprise.

When an object lookup is simpler than a switch

If every case only maps one value to another value, a plain object does the same job with less code and no break to forget:

const labels = { mon: "Monday", tue: "Tuesday", wed: "Wednesday" };
const label = labels[day] ?? "Unknown";

Keep the switch when cases run different statements, when you need deliberate fall-through, or when several cases share one body. Be careful with object lookups on untrusted keys: a key such as toString finds an inherited property on a plain object. Use Object.hasOwn(labels, day) to check first, or build the lookup with a Map.

If your switch does not behave as expected

  • Two branches run instead of one. A break is missing. Add it, or add a // falls through comment if the fall-through is intended.
  • Nothing matches a value that looks right. Check the type. typeof value will show whether you have a string where the case has a number.
  • A SyntaxError about a duplicate identifier. Wrap each clause that declares variables in braces.
  • default runs more than you expect. If it is not the last clause and has no break, it falls through to the clauses after it.

Frequently asked questions

Does a JavaScript switch use == or ===?
A switch compares the expression with each case using strict equality (===). No type conversion happens, so the number 1 does not match the string "1".
Is the break statement required in a switch case?
No, but without it execution continues into the next clause, even into default. Leave break out only on purpose, for example when stacking several case labels that share one body.
Can a switch case use a range or a comparison like x > 10?
Not directly, because each case value is compared with ===. The workaround is switch (true) with a boolean expression in each case, though an if...else chain is usually clearer for ranges.
Can default go in the middle of a switch?
Yes. default can appear anywhere and only one is allowed. If nothing matches, execution starts at default and continues down through any clauses after it, so put it last unless you have a reason not to.

Sources