Skip to content

Latest commit

Β 

History

History
71 lines (48 loc) Β· 1.94 KB

File metadata and controls

71 lines (48 loc) Β· 1.94 KB

prefer-includes-over-repeated-comparisons

πŸ“ Prefer .includes() over repeated equality comparisons.

πŸ’ΌπŸš« This rule is enabled in the βœ… recommended config. This rule is disabled in the β˜‘οΈ unopinionated config.

Comparing the same expression against multiple values is easier to scan as a membership check.

This rule only reports strict equality comparisons joined by ||. It ignores optional chains, side-effectful compared values, and NaN values because an Array#includes() rewrite would not have the same behavior.

This rule does not autofix because the best rewrite depends on context. Plain member expressions are still reported, so consider accessors and proxies before rewriting.

Examples

// ❌
value === 'a' || value === 'b' || value === 'c';

// βœ…
['a', 'b', 'c'].includes(value);
// ❌
args[0] === '-h' || args[0] === '--help' || args[0] === '--version';

// βœ…
['-h', '--help', '--version'].includes(args[0]);
// βœ…
value === 'a' || value === 'b';
// βœ…
value !== 'a' && value !== 'b';

Comparing several distinct expressions against the same value is not reported, since there is no single subject to check for membership.

// βœ…
state.a === undefined || state.b === undefined || state.c === undefined;

Options

Type: object

minimumComparisons

Type: integer
Minimum: 2
Default: 3

The minimum number of equality comparisons before reporting.

/* eslint unicorn/prefer-includes-over-repeated-comparisons: ["error", {"minimumComparisons": 4}] */

// βœ…
value === 'a' || value === 'b' || value === 'c';

// ❌
value === 'a' || value === 'b' || value === 'c' || value === 'd';