unnecessaryComparisons
Reports comparisons that are always true, always false, or can be simplified.
✅ This rule is included in the tslogicalandlogicalStrictpresets.
This rule detects comparison patterns that are logically unnecessary, impossible, or can be simplified. Such patterns often indicate logic errors, copy-paste mistakes, or overly complex code that should be refactored.
The rule covers several categories of problematic comparisons:
- Self-comparisons: Comparing a value to itself (e.g.,
x === x) - Impossible ranges: Range checks that can never be satisfied (e.g.,
x <= 400 && x > 500) - Redundant double comparisons: OR patterns that can be simplified (e.g.,
x === y || x < ycan becomex <= y) - Ineffective checks: Redundant bounds in AND chains (e.g.,
x < 200 && x <= 299where the second check is always true when the first is)
Examples
Section titled “Examples”Self-Comparisons
Section titled “Self-Comparisons”if (value === value) { // Always true}if (value < value) { // Always false}if (value === otherValue) { // Compare different values}// Use Number.isNaN() for NaN checksif (Number.isNaN(value)) { // ...}Impossible Ranges
Section titled “Impossible Ranges”// Can never be true: no value is both <= 400 AND > 500if (x <= 400 && x > 500) { // Unreachable code}// Impossible boundary conditionif (x < 5 && x >= 5) { // Never executes}// Valid range: x is between 400 and 500if (x >= 400 && x <= 500) { // ...}// Valid narrow rangeif (x > 5 && x < 10) { // ...}Redundant Double Comparisons
Section titled “Redundant Double Comparisons”// Can be simplified to: x <= yif (x === y || x < y) { // ...}// Can be simplified to: x >= yif (x === y || x > y) { // ...}// Use the simpler combined operatorif (x <= y) { // ...}if (x >= y) { // ...}Ineffective Checks
Section titled “Ineffective Checks”// x <= 299 is redundant when x < 200 is already checkedif (x < 200 && x <= 299) { // The second check adds nothing}// x >= 50 is redundant when x > 100 is already checkedif (x > 100 && x >= 50) { // ...}// Just use the stronger constraintif (x < 200) { // ...}// Or use both bounds when they're actually neededif (x > 100 && x < 200) { // Valid range check}Options
Section titled “Options”This rule is not configurable.
When Not To Use It
Section titled “When Not To Use It”If your codebase relies on dynamic getters or other side effects that could make seemingly-identical expressions return different values, you might want to disable this rule for those specific cases.
Further Reading
Section titled “Further Reading”Equivalents in Other Linters
Section titled “Equivalents in Other Linters”
Made with ❤️🔥 in Boston by
Josh Goldberg and contributors.