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 default comment after last case.
  • 'do-nothing-comment' Insert default case and add // Do nothing comment.
  • '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;
	}
}