unicorn/explicit-length-check
Require length and size to be compared with a number
fixable
if (items.length) relies on 0 being falsy. if (items.length > 0) says what you're testing. It also keeps a number out of places where you want a boolean. items.length && render(items) evaluates to 0 for an empty list, not false.
The rule also settles on one spelling for each check: === 0 for empty and > 0 for not empty. It reports other ways to write them, such as < 1, >= 1 and !== 0.
--fix rewrites the check wherever only its truthiness matters. In const first = items.length && items[0] the value itself is used, so that's reported but not fixed.
Configure#
Off by default. To turn it on:
bunfig.toml
[lint.rules]
"unicorn/explicit-length-check" = "error" # or "warn"Every option, set to its default:
bunfig.toml
[lint.rules]
"unicorn/explicit-length-check" = ["error", {
non-zero = "greater-than",
}]Examples#
example.js4 problems
if (items.lengthUse .length > 0 when checking length is not zero.) {
render(items);
}
if (!selected.sizeUse .size === 0 when checking size is zero.) {
disable(button);
}
const hasErrors = errors.length >= 1Use .length > 0 when checking length is not zero.;
const first = items.lengthUse .length > 0 when checking length is not zero. && items[0];example.jsNo problems
if (items.length > 0) {
render(items);
}
if (selected.size === 0) {
disable(button);
}
const hasErrors = errors.length > 0;
const first = items.length > 0 && items[0];Optional chains, this.length and a fallback to a number are left alone:
example.jsNo problems
if (items?.length) {
render(items);
}
class Queue extends Array {
isEmpty() {
return !this.length;
}
}
const columns = headers.length || 1;Options#
| Option | Default | What it does |
|---|---|---|
non-zero | "greater-than" | How to write "not empty": "greater-than" requires > 0, "not-equal" requires !== 0. |
example.jswith
{ "non-zero": "not-equal" }No problemsif (items.length !== 0) {
render(items);
}example.jswith
{ "non-zero": "not-equal" }1 problemif (items.length > 0Use .length !== 0 when checking length is not zero.) {
render(items);
}