unicorn/no-useless-length-check

Disallow checking an array's length next to .some() or .every() where it changes nothing

some() returns false for an empty array, so items.length > 0 && items.some(...) gives the same answer without the length check. every() returns true for an empty array, so items.length === 0 || items.every(...) does too.

length !== 0 counts the same as length > 0. The check can come before or after the call, and both must be on the same variable.

Configure#

Off by default. To turn it on:

bunfig.toml
[lint.rules]
"unicorn/no-useless-length-check" = "error" # or "warn"

Examples#

example.js3 problems
if (errors.length > 0 && errors.some(error => error.fatal)) {
  stop();
}

const isDone = tasks.length === 0 || tasks.every(task => task.done);
const hasDraft = posts.some(post => post.draft) && posts.length !== 0;
example.jsNo problems
if (errors.some(error => error.fatal)) {
  stop();
}

const isDone = tasks.every(task => task.done);
const hasDraft = posts.some(post => post.draft);

Here the check does change the result, because every() alone is true for an empty array:

example.jsNo problems
const allPassed = tests.length > 0 && tests.every(test => test.passed);