Enforce explicitly checking the length of an object and enforce the comparison style.
This rule is fixable.
Enforce comparison with === 0
when checking for zero length.
if (!foo.length) {}
while (foo.length == 0) {}
do {} while (foo.length < 1);
if (; 0 === foo.length;) {}
const unicorn = 0 == foo.length ? 1 : 2;
if (1 > foo.length) {}
// Negative style is forbid too
if (!(foo.length > 0)) {}
if (foo.length === 0) {}
const unicorn = foo.length === 0 ? 1 : 2;
Enforce comparison with > 0
when checking for non-zero length.
if (foo.length !== 0) {}
while (foo.length != 0) {}
do {} while (foo.length >= 1);
for (; 0 !== foo.length; ) {}
const unicorn = 0 != foo.length ? 1 : 2;
if (0 < foo.length) {}
if (1 <= foo.length) {}
// Negative style is forbid too
if (!(foo.length === 0)) {}
if (foo.length > 0) {}
const unicorn = foo.length > 0 ? 1 : 2;
You can define your preferred way of checking non-zero length by providing a non-zero
option (greater-than
by default):
{
'unicorn/explicit-length-check': [
'error',
{
'non-zero': 'not-equal'
}
]
}
The non-zero
option can be configured with one of the following:
greater-than
(default)- Enforces non-zero to be checked with:
foo.length > 0
- Enforces non-zero to be checked with:
not-equal
- Enforces non-zero to be checked with:
foo.length !== 0
- Enforces non-zero to be checked with:
greater-than-or-equal
- Enforces non-zero to be checked with:
foo.length >= 1
- Enforces non-zero to be checked with: