JavaScript switch Statement: case, break, default and Fall-Through

When one value can match many fixed options, such as a browser name, an HTTP method or a test environment, a long else if chain becomes noisy. The switch statement compares one value against a list of case labels and runs the matching code. In this lesson you will learn how switch works, why break matters, how to group cases, the switch (true) pattern for ranges, and when a lookup object is the better choice.

Advertisement

📖 What You’ll Learn: switch syntax, case and default, strict comparison in cases, break and fall-through, grouping several cases, returning from a switch inside a function, block scope inside cases, switch (true) for ranges, switch versus if/else versus lookup objects, and a tester scenario that picks environment settings.


🔀 What Is a switch Statement?

Definition: a switch statement evaluates an expression once and compares its value with each case using strict equality (===). It runs the code of the first matching case and continues until it reaches break or the end of the switch. The optional default case runs when nothing matches.

📄 Syntax

switch (expression) {
  case value1:
    // runs when expression === value1
    break;
  case value2:
    // runs when expression === value2
    break;
  default:
    // runs when no case matches
}

📄 switch.js

const browser = "firefox";

switch (browser) {
  case "chromium":
    console.log("Engine: Blink");
    break;
  case "firefox":
    console.log("Engine: Gecko");
    break;
  case "webkit":
    console.log("Engine: WebKit");
    break;
  default:
    console.log(`Unknown browser: ${browser}`);
}

⌨️ Terminal

node switch.js

🖥️ Output

Engine: Gecko

🎯 Cases Use Strict Equality (===)

Each case is compared with ===, so the type must match. A number from a page or a command-line argument arrives as a string and will not match a numeric case:

📄 strict.js

function describe(status) {
  switch (status) {
    case 200:
      return "OK";
    case 404:
      return "Not Found";
    default:
      return `No match for ${JSON.stringify(status)} (${typeof status})`;
  }
}

console.log(describe(200));
console.log(describe("200"));          // string: no case matches
console.log(describe(Number("200")));  // convert first

⌨️ Terminal

node strict.js

🖥️ Output

OK
No match for "200" (string)
OK

⚠️ Watch out: Convert input to the right type before the switch, for example switch (Number(code)), or the default branch will run silently.


⛔ break and Fall-Through

Without break, execution falls through into the next case and runs its code as well, whether or not that case matches:

📄 fall-through.js

const level = "warn";

switch (level) {
  case "error":
    console.log("send alert");
  case "warn":
    console.log("write to log file");
  case "info":
    console.log("print to console");
}

⌨️ Terminal

node fall-through.js

🖥️ Output

write to log file
print to console

The "warn" case matched, and because there is no break, the "info" code ran too. Sometimes this is intentional, as here, where each level also does everything below it. Usually it is a bug.

💡 Tip: If you use fall-through on purpose, add a comment such as // falls through. ESLint’s no-fallthrough rule reports missing break statements unless that comment is present.


Advertisement

🧺 Grouping Several Cases

Empty cases that follow each other share the same code. This is the most common, and perfectly clear, use of fall-through:

📄 grouping.js

function dayType(day) {
  switch (day.toLowerCase()) {
    case "saturday":
    case "sunday":
      return "weekend";
    case "monday":
    case "tuesday":
    case "wednesday":
    case "thursday":
    case "friday":
      return "weekday";
    default:
      return "invalid day";
  }
}

for (const d of ["Sunday", "wednesday", "Funday"]) {
  console.log(d, "->", dayType(d));
}

⌨️ Terminal

node grouping.js

🖥️ Output

Sunday -> weekend
wednesday -> weekday
Funday -> invalid day

Inside a function, return leaves both the switch and the function, so no break is needed after it.


📦 Block Scope Inside Cases

All cases share one block, so declaring the same let or const name in two cases is an error:

📄 scope-bug.js

const method = "POST";
switch (method) {
  case "GET":
    const message = "reading data";
    console.log(message);
    break;
  case "POST":
    const message = "creating data";
    console.log(message);
    break;
}

⌨️ Terminal

node scope-bug.js

🖥️ Output

/home/you/js-course/scope-bug.js:8
    const message = "creating data";
          ^

SyntaxError: Identifier 'message' has already been declared

Node.js v26.13.0

Fix: wrap each case body in its own braces to give it a separate block:

📄 scope-fixed.js

const method = "POST";
switch (method) {
  case "GET": {
    const message = "reading data";
    console.log(message);
    break;
  }
  case "POST": {
    const message = "creating data";
    console.log(message);
    break;
  }
}

⌨️ Terminal

node scope-fixed.js

🖥️ Output

creating data

Advertisement

📊 Ranges with switch (true)

Cases must be exact values, so ranges such as “score from 75 to 89” do not fit directly. A known pattern is switch (true): each case is a condition, and the first one that equals true wins.

📄 switch-true.js

function rateResponse(ms) {
  switch (true) {
    case ms < 200:
      return "excellent";
    case ms < 1000:
      return "acceptable";
    case ms < 3000:
      return "slow";
    default:
      return "timeout risk";
  }
}

for (const ms of [150, 640, 2400, 5000]) {
  console.log(`${ms} ms: ${rateResponse(ms)}`);
}

⌨️ Terminal

node switch-true.js

🖥️ Output

150 ms: excellent
640 ms: acceptable
2400 ms: slow
5000 ms: timeout risk

📌 Note: switch (true) works, but many teams prefer an if / else if chain for ranges because it is more familiar. Pick one style per project.


⚖️ switch vs if/else vs Lookup Object

UseWhen
if / else ifConditions are ranges or combinations (age >= 18 && hasId), or there are only two or three branches
switchOne value is compared with many exact options, and each option runs different code
Lookup object / MapEach option only maps to a value (or a function), and the list may grow

The same mapping written as a switch and as a lookup object:

📄 compare.js

function timeoutFor(env) {
  switch (env) {
    case "local":
      return 5000;
    case "qa":
      return 15000;
    case "prod":
      return 30000;
    default:
      throw new Error(`Unknown environment: ${env}`);
  }
}

const TIMEOUTS = { local: 5000, qa: 15000, prod: 30000 };
const timeoutFor2 = (env) => {
  if (!(env in TIMEOUTS)) throw new Error(`Unknown environment: ${env}`);
  return TIMEOUTS[env];
};

console.log(timeoutFor("qa"), timeoutFor2("qa"));
try {
  timeoutFor("staging");
} catch (e) {
  console.log(e.message);
}

⌨️ Terminal

node compare.js

🖥️ Output

15000 15000
Unknown environment: staging

💡 Tip: Throwing in default for unexpected values is a good habit in test code. A typo such as "QA" instead of "qa" then fails loudly instead of running tests with the wrong settings.


🧪 Tester Scenario: Choose Settings per Environment and Action

This script reads the environment from the command line (with a default), picks the base URL and retry count, and maps test actions to log messages:

📄 env-switch.js

const env = (process.argv[2] || "qa").toLowerCase();

let baseURL;
let retries;
switch (env) {
  case "local":
    baseURL = "http://localhost:3000";
    retries = 0;
    break;
  case "qa":
  case "staging":
    baseURL = `https://${env}.example.com`;
    retries = 1;
    break;
  case "prod":
    baseURL = "https://www.example.com";
    retries = 2;
    break;
  default:
    throw new Error(`Unsupported environment "${env}"`);
}
console.log({ env, baseURL, retries });

const steps = ["open", "login", "search", "logout", "upload"];
for (const step of steps) {
  switch (step) {
    case "open":
      console.log(`→ open ${baseURL}`);
      break;
    case "login":
    case "logout":
      console.log(`→ ${step} (auth step)`);
      break;
    case "search":
      console.log("→ search for \"laptop\"");
      break;
    default:
      console.log(`→ skipped unknown step "${step}"`);
  }
}

⌨️ Terminal

node env-switch.js

🖥️ Output

{ env: 'qa', baseURL: 'https://qa.example.com', retries: 1 }
→ open https://qa.example.com
→ login (auth step)
→ search for "laptop"
→ logout (auth step)
→ skipped unknown step "upload"

Run it with an argument to try other environments: node env-switch.js staging.


Advertisement

📝 Practice Questions with Answers

Try each question on your own first, then open the answer to check your work. Run the code with node practice.js.

Q1. Write a switch that prints the number of days in a month name (ignore leap years). Group months with 31 and 30 days.

Show answer

📄 practice1.js

function daysIn(month) {
  switch (month) {
    case "feb":
      return 28;
    case "apr":
    case "jun":
    case "sep":
    case "nov":
      return 30;
    case "jan": case "mar": case "may": case "jul":
    case "aug": case "oct": case "dec":
      return 31;
    default:
      throw new Error(`Unknown month ${month}`);
  }
}

console.log(daysIn("feb"), daysIn("jun"), daysIn("dec"));

🖥️ Output

28 30 31

Q2. Predict the output, then run it.

const x = 2;
switch (x) {
  case 1:
    console.log("one");
  case 2:
    console.log("two");
  case 3:
    console.log("three");
    break;
  default:
    console.log("other");
}
Show answer

📄 practice2.js

const x = 2;
switch (x) {
  case 1:
    console.log("one");
  case 2:
    console.log("two");
  case 3:
    console.log("three");
    break;
  default:
    console.log("other");
}

🖥️ Output

two
three

Case 2 matches, prints “two”, falls through into case 3, prints “three” and stops at break.

Q3. Build a tiny calculator: calc(a, op, b) supports +, -, *, / and throws for unknown operators and division by zero.

Show answer

📄 practice3.js

function calc(a, op, b) {
  switch (op) {
    case "+": return a + b;
    case "-": return a - b;
    case "*": return a * b;
    case "/":
      if (b === 0) throw new Error("Division by zero");
      return a / b;
    default:
      throw new Error(`Unknown operator ${op}`);
  }
}

console.log(calc(6, "+", 2), calc(6, "-", 2), calc(6, "*", 2), calc(6, "/", 2));
try { calc(1, "/", 0); } catch (e) { console.log(e.message); }
try { calc(1, "^", 2); } catch (e) { console.log(e.message); }

🖥️ Output

8 4 12 3
Division by zero
Unknown operator ^

Q4. Use switch (true) to convert a percentage to a grade: 90+ A, 75+ B, 60+ C, otherwise F.

Show answer

📄 practice4.js

function grade(p) {
  switch (true) {
    case p >= 90: return "A";
    case p >= 75: return "B";
    case p >= 60: return "C";
    default: return "F";
  }
}

console.log([92, 75, 61, 10].map(grade).join(" "));

🖥️ Output

A B C F

Q5. Why does this switch always print “unknown”? Fix it.

const input = "2";
switch (input) {
  case 1: console.log("one"); break;
  case 2: console.log("two"); break;
  default: console.log("unknown");
}
Show answer

Cases use strict equality: the string "2" never equals the number 2. Convert the input first:

📄 practice5.js

const input = "2";
switch (Number(input)) {
  case 1: console.log("one"); break;
  case 2: console.log("two"); break;
  default: console.log("unknown");
}

🖥️ Output

two

Q6. Rewrite this switch as a lookup object with a default of "⚪".

switch (status) {
  case "passed": icon = "✅"; break;
  case "failed": icon = "❌"; break;
  case "skipped": icon = "⏭️"; break;
  default: icon = "⚪";
}
Show answer

📄 practice6.js

const ICONS = { passed: "✅", failed: "❌", skipped: "⏭️" };
for (const status of ["passed", "failed", "flaky"]) {
  console.log(status, ICONS[status] ?? "⚪");
}

🖥️ Output

passed ✅
failed ❌
flaky ⚪

🧠 MCQ Quiz: switch Statement

10 questions on this lesson. Pick one answer for each, then press Check answers to see your score and an explanation for every question.

  1. Which comparison does switch use to match cases?
  2. What happens if a matching case has no break?
  3. When does the default case run?
  4. How do you make two cases run the same code?
  5. Why does declaring const x in two different cases fail?
  6. What is switch (true) used for?
  7. Inside a function, why is break not needed after return in a case?
  8. Which is usually the best choice for mapping a few fixed keys to values?
  9. What does this print?
    switch (3) {
      default: console.log("d");
      case 1: console.log("1");
    }
  10. Which ESLint rule reports an accidental missing break?

💼 Interview Questions and Answers

Q1. What is fall-through in a switch statement?

After a case matches, JavaScript keeps executing the following case bodies until it hits break, return, throw or the end of the switch. Intentional fall-through is used to group cases that share code; accidental fall-through (a forgotten break) is a common bug that ESLint’s no-fallthrough rule catches.

Q2. When would you choose switch over if/else?

When one expression is compared against many exact values and each value needs different code, such as actions per HTTP method or per test step. For ranges and combined conditions if/else is clearer; for value-only mappings a lookup object or Map is shorter and data-driven.

Q3. Why might a switch never match even though the value “looks” right?

Cases use ===, so types must match exactly: "200" vs 200, "QA" vs "qa", or a value with trailing spaces from a page. Normalise the input first (Number(), .trim().toLowerCase()) and make default throw or log the unexpected value so the mismatch is visible.

Q4. Can a case contain an expression instead of a literal?

Yes. Case labels are evaluated as expressions, so case MAX_RETRIES: or case a + b: are valid. They are evaluated in order only until a match is found. switch (true) takes advantage of this by using conditions as case expressions.

📄 case-expr.js

const LIMIT = 3;
const attempts = 3;
switch (attempts) {
  case LIMIT - 1: console.log("last try left"); break;
  case LIMIT: console.log("limit reached"); break;
}

⌨️ Terminal

node case-expr.js

🖥️ Output

limit reached

Advertisement

❓ Frequently Asked Questions

🤔 Is break required in every case?

Not by the language, but without it execution falls through to the next case. Leave it out only on purpose (and comment it), or when the case ends with return or throw.

🤔 Does the default case have to be last?

No, it can appear anywhere, but putting it last is the convention and avoids confusing fall-through.

🤔 Can switch compare strings?

Yes. Any value works, compared with ===. Normalise case and whitespace first when the input comes from users or web pages.

🤔 Is switch faster than if/else?

For typical code the difference is negligible. Choose the form that is clearest for the logic.


🏁 Summary

  • switch compares one value with many case labels using ===; default handles no match.
  • Without break (or return), execution falls through into the next case.
  • Group cases by listing labels together; wrap case bodies in braces when they declare variables.
  • switch (true) can handle ranges, but if/else if is often clearer.
  • Use lookup objects for simple value mappings, and throw in default for unexpected input.

Next, continue with Lesson 15: Loops.

🎬 Watch JavaScript and automation tutorials on YouTube!

Subscribe to SqaToolsByDY • Practice on sqatools.in