Skip to main content

no-self-compare

Comparing a variable to itself is almost always a mistake, either a typo or refactoring error.
Rule Type: Problem
Fixable: No

Why This Rule Exists

There are almost no situations where you would want to compare something to itself. The only common case is testing for NaN, but there are better ways to do that.

Rule Details

This rule flags any comparison where both sides are syntactically identical.

Examples

Incorrect Code

Correct Code

Common Mistakes

Testing for NaN (Wrong)

While x !== x does test for NaN (since NaN !== NaN), it’s confusing and there are better alternatives.

Copy-Paste Errors

Refactoring Errors

Known Limitations

This rule uses simple syntactic comparison and may produce false positives in rare cases:
For these rare cases, restructure your code to avoid self-comparison, or disable the rule for that specific line with a comment explaining why.

Better Alternatives

NaN Detection

Value Validation

When Not to Use It

This rule has very few legitimate exceptions. Only disable it if:
  1. You have complex expressions where static analysis can’t determine they’re actually different
  2. You’re using a code generation tool that produces self-comparisons
For NaN checking, use Number.isNaN() instead of disabling the rule.

Disabling for Specific Lines