prefer-switch
March 27, 2026 ยท View on GitHub
๐ Prefer switch over multiple else-if.
๐ผ This rule is enabled in the following configs: โ
recommended, โ๏ธ unopinionated.
๐ง This rule is automatically fixable by the --fix CLI option.
A switch statement is easier to read than multiple if statements with simple equality comparisons.
Examples
// โ
if (foo === 1) {
// 1
} else if (foo === 2) {
// 2
} else if (foo === 3) {
// 3
} else {
// default
}
// โ
if (foo === 1) {
// 1
} else if (foo === 2) {
// 2
}
// โ
switch (foo) {
case 1: {
// 1
break;
}
case 2: {
// 2
break;
}
case 3: {
// 3
break;
}
default: {
// default
}
}
Options
Type: object
minimumCases
Type: integer
Minimum: 2
Default: 3
The minimum number of cases before reporting.
The default branch doesn't count. Multiple comparisons on the same if block is considered one case.
Examples:
/* eslint unicorn/prefer-switch: ["error", {"minimumCases": 4}] */
// โ
if (foo === 1) {}
else if (foo === 2) {}
else if (foo === 3) {}
// โ
if (foo === 1) {}
else if (foo === 2) {}
else if (foo === 3) {}
else {}
// โ
if (foo === 1) {}
else if (foo === 2 || foo === 3) {}
else if (foo === 4) {}
/* eslint unicorn/prefer-switch: ["error", {"minimumCases": 2}] */
// โ
if (foo === 1) {}
else if (foo === 2) {}
emptyDefaultCase
Type: string
Default: 'no-default-comment'
To avoid conflict with the default-case rule, choose the fix style you prefer:
'no-default-comment'(default) Insert// No defaultcomment after last case.'do-nothing-comment'Insertdefaultcase and add// Do nothingcomment.'no-default-case'Don't insert default case or comment.
if (foo === 1) {}
else if (foo === 2) {}
else if (foo === 3) {}
Fixed
/* eslint unicorn/prefer-switch: ["error", { "emptyDefaultCase": "no-default-comment" }] */
switch (foo) {
case 1: {
break;
}
case 2: {
break;
}
case 3: {
break;
}
// No default
}
/* eslint unicorn/prefer-switch: ["error", { "emptyDefaultCase": "do-nothing-comment" }] */
switch (foo) {
case 1: {
break;
}
case 2: {
break;
}
case 3: {
break;
}
default:
// Do nothing
}
/* eslint unicorn/prefer-switch: ["error", { "emptyDefaultCase": "no-default-case" }] */
switch (foo) {
case 1: {
break;
}
case 2: {
break;
}
case 3: {
break;
}
}