Skip to content

Latest commit

Β 

History

History
54 lines (36 loc) Β· 2.48 KB

no-redundant-comparison.md

File metadata and controls

54 lines (36 loc) Β· 2.48 KB

no-redundant-comparison

πŸ“ Disallow comparisons made redundant by an equality check in the same logical AND.

πŸ’Ό This rule is enabled in the following configs: βœ… recommended, β˜‘οΈ unopinionated.

πŸ”§πŸ’‘ This rule is automatically fixable by the --fix CLI option and manually fixable by editor suggestions.

When an && chain contains an equality check (=== or !==) between two references, a comparison on one of those references can already be implied by a comparison on the other. The redundant comparison adds nothing and just costs an extra evaluation.

This is not limited to identical comparisons. A stronger numeric bound implies a weaker one (a > 2 implies a > 0), and a disequality propagates an equality (a === 'x' && a !== b implies b !== 'x').

Examples

// ❌ β€” `b > 0` is implied by `a > 0` and `a === b`
if (a > 0 && b > 0 && a === b) {}

// βœ…
if (a > 0 && a === b) {}
// ❌ β€” `a > 0` is implied by the stronger `b > 2` and `a === b`
if (a > 0 && b > 2 && a === b) {}

// βœ…
if (b > 2 && a === b) {}
// ❌ β€” `b !== 'test'` is implied by `a !== 'test'` and `a === b`
if (a !== 'test' && b !== 'test' && a === b) {}

// βœ…
if (a !== 'test' && a === b) {}
// ❌ β€” `b !== 'test'` is implied by `a === 'test'` and `a !== b`
if (a === 'test' && b !== 'test' && a !== b) {}

// βœ…
if (a === 'test' && a !== b) {}

This rule only applies to && chains. In a || chain the operands are not all true at once, so the equality check cannot be used to imply another operand.

Chains with explicit side effects, such as calls (including tagged templates), assignments, or updates, between the first and the last comparison are skipped because they can change the values between comparisons. Side effects before the first or after the last comparison do not prevent the check.

Removing a comparison drops its evaluation. When that evaluation could run user code β€” a getter, or a valueOf/toString coercion from an ordering check (>, >=, <, <=) β€” the rule offers a suggestion instead of an autofix to avoid changing behavior. A plain ===/!== check is side-effect free and is autofixed.