Why I use rswitch instead of long switch blocks

Published: (February 2, 2026 at 05:31 PM EST)
1 min read
Source: Dev.to

Source: Dev.to

Install

npm i rswitch

Basic idea

You give rswitch:

  • a key (the value you want to check)
  • a cases object (what to return for each case)
  • an optional options object

Simple example

import rswitch from "rswitch";

const role = "dev";

const result = rswitch(role, {
  designer: "Designer",
  "dev, web": "Freelancer", // match many keys
  "": "Unknown",            // default case
});

console.log(result); // Freelancer

✅ Tip: "" (empty string) is the default case.

Example 1: Handle status codes (clean and clear)

import rswitch from "rswitch";

function statusMessage(code) {
  return rswitch(code, {
    "200, 201, 204": "✅ Success",
    "400, 401, 403": "⛔ Client error",
    "500, 502, 503": "🔥 Server error",
    "": "🤷 Unknown status",
  });
}

console.log(statusMessage(503)); // 🔥 Server error

No break, no fall‑through, easy to read.

Example 2: Run functions as actions

Actions can be values or functions.

import rswitch from "rswitch";

const command = "build";

const result = rswitch(command, {
  build: () => "Building...",
  test: () => "Testing...",
  "": () => "Use: build or test",
});

console.log(result); // Building...

Why rswitch is better than switch (for many cases)

  • Short code
  • Easy to read
  • Group multiple cases like "dev, web"
  • Default case is simple: ""
  • Works great in JavaScript + TypeScript

If your switch is getting long, rswitch can make it cleaner.

Back to Blog

Related posts

Read more »