Skip to content
← Back to rules

unicorn/no-useless-length-check Correctness

✅ This rule is turned on by default.
🛠️ An auto-fix is available for this rule for some violations.

What it does ​

It checks for an unnecessary array length check in a logical expression or before a for...of loop.

The cases are:

  • array.length === 0 || array.every(Boolean) (array.every returns true if array is empty)
  • array.length > 0 && array.some(Boolean) (array.some returns false if array is empty)
  • if (array.length > 0) { for (const x of array) {} } (for...of skips empty arrays)

Why is this bad? ​

An extra unnecessary length check is done.

Examples ​

Examples of incorrect code for this rule:

javascript
if (array.length === 0 || array.every(Boolean)) {
  // do something!
}
if (array.length > 0) {
  for (const x of array) {
    use(x);
  }
}

Examples of correct code for this rule:

javascript
if (array.every(Boolean)) {
  // do something!
}
for (const x of array) {
  use(x);
}

How to use ​

To enable this rule using the config file or in the CLI, you can use:

json
{
  "rules": {
    "unicorn/no-useless-length-check": "error"
  }
}
ts
import { defineConfig } from "oxlint";

export default defineConfig({
  rules: {
    "unicorn/no-useless-length-check": "error",
  },
});
bash
oxlint --deny unicorn/no-useless-length-check

Version ​

This rule was added in v0.0.19.

References ​