Javascript: why not recommended to use `array.length` directly in if statements ?

Created on 8 Jul 2018  Â·  2Comments  Â·  Source: airbnb/javascript

In NO. 15.3.

// bad
if (collection.length) {
  // ...
}

// good
if (collection.length > 0) {
  // ...
}

why use collection.length>0 is better than collection.length?

question

Most helpful comment

Because .length isn't a boolean - which means you're relying on the implicit conversion of a number to a boolean. Using > 0 is explicit (and explicit > implicit), and avoids any possible confusion about what you mean.

All 2 comments

Because .length isn't a boolean - which means you're relying on the implicit conversion of a number to a boolean. Using > 0 is explicit (and explicit > implicit), and avoids any possible confusion about what you mean.

I see,thanks for your wonderful reply. @ljharb

Was this page helpful?
0 / 5 - 0 ratings