Skip to content
Sarj Code Standards

prefer-switch-for-repeated-equality

Prefer switch over long if/else-if chains that compare one value for strict equality.

Why

A switch makes finite dispatch cases visually uniform and easier to extend without duplicating the discriminant.

Fix

Replace three or more strict-equality branches over the same discriminant with a switch; keep if statements for ranges, guards, and heterogeneous predicates.

Examples

Before — flagged Use native identifier identity
src/dispatch.ts
function probe(kind) {
if (kind === "a") return 1;
else if (kind === "b") return 2;
else if (kind === "c") return 3;
return 0;
}
console.log(JSON.stringify(["a", "b", "c", "d"].map(probe)));
After — preferred Use native identifier identity
src/dispatch.ts
function probe(kind) {
const other = "other";
if (kind === "a") return 1;
else if (other === "b") return 2;
else if (kind === "c") return 3;
return 0;
}
console.log(JSON.stringify(["a", "b", "c", "d"].map(probe)));
Before — flagged Avoid repeating the discriminant
src/render.ts
function render(kind: string) {
if (kind === "a") return "alpha";
else if (kind === "b") return "beta";
else if (kind === "c") return "gamma";
return "unknown";
}
After — preferred Make finite dispatch explicit
src/render.ts
function render(kind: string) {
switch (kind) {
case "a":
return "alpha";
case "b":
return "beta";
case "c":
return "gamma";
default:
return "unknown";
}
}