Skip to content

No Useless Empty String Comparison

SuggestionAuto-fixable
small-rules/no-useless-empty-string-comparison

Disallow equality comparisons against an empty-string literal.

Rationale

value === "" compares a string to one literal. value.length === 0 checks that the string is empty. The length form only compiles when value is a string. TypeScript then catches a string | undefined that the literal comparison would treat as non-empty.

  • Says what it checks: a reader of name === "" has to look inside the quotes to see that the literal is empty and not " " or "0". name.length === 0 puts that in the identifier.

  • Keeps the polarity: value !== "" becomes value.length > 0, the form unicorn’s explicit-length-check also asks for.
  • No falsy shortcut: !value is shorter, but it also accepts null, undefined, and anything else falsy, and in the trimmed form it benchmarks slower than either comparison. The length check is as fast as the literal comparison it replaces.

The rule reports === and !== against an empty string literal and offers the .length form as a suggestion you apply by hand. The rewrite parenthesizes compound operands, so (a || b) === "" becomes (a || b).length === 0. The rule reports loose == and != without a rewrite, because 0 == "" and false == "" are true and a length check would flip them.

if (name.length === 0) return;
if (name.trim().length !== 0) submit(name);

The rule has no type information. On a string | undefined operand, .length throws where === "" returned false. That is why the autofix is off by default. Set allowAutofix to true once your strict comparisons are known to be plain strings, and the fixer rewrites them under oxlint --fix. Comparisons against non-empty strings, template literals, and String() calls aren’t reported.

Diagnostic Messages

looseEmptyStringComparison
Comparing to '' with a loose operator also matches 0 and false. Use `===` and then `.length === 0`.
suggestLengthComparison
Replace with `{{replacement}}`.
useLengthComparison
Use `{{replacement}}` instead of comparing the string to ''.

Configuration

This rule accepts one options object after the severity.

allowAutofixOptional

Rewrite strict comparisons to `.length` automatically. Off by default because the rule cannot see types, and `.length` throws on a nullish operand.

{
"jsPlugins": [
"@pobammer-ts/small-rules"
],
"rules": {
"small-rules/no-useless-empty-string-comparison": [
"error",
{
"allowAutofix": false
}
]
}
}

Examples

Equality against an empty string
if (value === '') flag = true;
Length comparison
if (value.length === 0) flag = true;