Skip to content

Latest commit

 

History

History
123 lines (89 loc) · 1.73 KB

explicit-length-check.md

File metadata and controls

123 lines (89 loc) · 1.73 KB

Enforce explicitly comparing the length property of a value

Enforce explicitly checking the length of an object and enforce the comparison style.

This rule is fixable.

Zero comparisons

Enforce comparison with === 0 when checking for zero length.

Fail

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)) {}

Pass

if (foo.length === 0) {}
const unicorn = foo.length === 0 ? 1 : 2;

Non-zero comparisons

Enforce comparison with > 0 when checking for non-zero length.

Fail

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)) {}

Pass

if (foo.length > 0) {}
const unicorn = foo.length > 0 ? 1 : 2;

Options

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
  • not-equal
    • Enforces non-zero to be checked with: foo.length !== 0
  • greater-than-or-equal
    • Enforces non-zero to be checked with: foo.length >= 1