Skip to content

Latest commit

 

History

History
176 lines (143 loc) · 2.84 KB

prefer-switch.md

File metadata and controls

176 lines (143 loc) · 2.84 KB

Prefer switch over multiple else-if

💼 This rule is enabled in the ✅ recommended config.

🔧 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.

Fail

if (foo === 1) {
	// 1
} else if (foo === 2) {
	// 2
} else if (foo === 3) {
	// 3
} else {
	// default
}

Pass

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) {}

// Passes, only 3 cases.
// eslint unicorn/prefer-switch: ["error", {"minimumCases": 4}]
if (foo === 1) {}
else if (foo === 2) {}
else if (foo === 3) {}
else {}

// Passes, only 3 cases.
// eslint unicorn/prefer-switch: ["error", {"minimumCases": 4}]
if (foo === 1) {}
else if (foo === 2 || foo === 3) {}
else if (foo === 4) {}

// Passes, only 3 cases.
// eslint unicorn/prefer-switch: ["error", {"minimumCases": 2}]
if (foo === 1) {}
else if (foo === 2) {}

// Fails

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;
	}
}