JavaScript switch

Beginner
5 min read
Updated: Nov 2026
3 examples

Definition and Usage

switch compares one value to several case labels with strict equality (===). Use break to stop after a match, and default when nothing matches.

JavaScript Syntax

JavaScript
const day = "Mon";
switch (day) {
  case "Mon":
    console.log("start");
    break;
  case "Fri":
    console.log("almost");
    break;
  default:
    console.log("other");
}
Try it Editor

How It Works

  1. Match Mon. The first case runs.
  2. break stops. Without break, later cases would also run (fall-through).

Examples

Example 1 — Intentional fall-through

Share one body for several cases.

JavaScript
const k = "a";
switch (k) {
  case "a":
  case "b":
    console.log("a or b");
    break;
  default:
    console.log("other");
}
Try it Editor

How It Works

  1. case a has no break, so it falls into the shared body.
  2. Then break ends the switch.

Example 2 — Numbers work too

Cases use === matching.

JavaScript
switch (2) {
  case 1: console.log("one"); break;
  case 2: console.log("two"); break;
}
Try it Editor

How It Works

  1. 2 === 2 matches.
  2. break prevents fall-through.

Example 3 — When to prefer if

Ranges and complex conditions fit if better.

JavaScript
const n = 7;
if (n > 5) console.log("big");
else console.log("small");
Try it Editor

How It Works

  1. switch is for discrete values.
  2. Comparisons like > belong in if.

Frequently Asked Questions

Strict equality ===. "2" will not match case 2.
Execution falls into the next case. Usually a bug unless you want shared logic.

CODETOFUN NEWS

Stay Ahead in Tech

Get the latest IT news, programming updates, and technology trends directly on your phone.

Your daily dose of tech, straight to your feed.

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

6 people found this page helpful