Skip to content

JavaScript Tutorial Conditions

JavaScript switch Statement

Lesson 43 of 258 2 min read By Deepak Paswan Updated Oct 4, 2026

A switch statement compares one value against a list of possible matches. It is a tidy alternative to a long if / else if chain when you always test the same variable.

script.js
JS
const day = "tue";

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

How it works

  1. JavaScript evaluates the expression in switch (...) once.
  2. It compares the result with each case using strict equality (===).
  3. It runs the code after the first matching case.
  4. break jumps out of the switch. default runs when nothing matched.

Do not forget break

Without break, execution falls through into the next case.

script.js
JS
const level = 1;

switch (level) {
  case 1:
    console.log("one");
  case 2:
    console.log("two (fell through)");
    break;
  case 3:
    console.log("three");
}

The output has two lines, because level 1 had no break. Fall-through is useful on purpose (see sat and sun above, where two cases share one block), but it is also an easy mistake.

Returning from a switch

Inside a function, return replaces break:

script.js
JS
function statusText(code) {
  switch (code) {
    case 200: return "OK";
    case 404: return "Not found";
    case 500: return "Server error";
    default:  return "Unknown";
  }
}

console.log(statusText(404)); // → Not found

switch or if?

  • Use switch when comparing one value against several exact matches.
  • Use if / else if for ranges and mixed conditions (score >= 90).
  • For a lookup that just maps a key to a value, an object is often neater:
script.js
JS
const messages = { 200: "OK", 404: "Not found", 500: "Server error" };
console.log(messages[404] ?? "Unknown"); // → Not found
info
Scope tip
All cases share one scope. If you declare let variables inside a case, wrap the case body in { } to avoid clashes.