Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

221
Views
Difference between if (array.length > 0) and if (array?.length) in Javascript (Why is array.length > 0 falsey?)

I'm a super green developer that started my first job last week. I got a comment from another developer to add a condition to check if array is undefined and to check if array is in fact an array.

Initially I used:

$: hasActiveCoupons = $cart.coupons && $cart.coupons.length > 0;

if (hasActiveCoupons && $cart.coupons.find((coupon) => coupon.id === couponCode)) {
...
}

But then she pointed out to me that $cart.coupons.length > 0 would return a falsey value. And corrected it by writing:

if ($cart.coupons?.length && $cart.coupons.find((coupon) => coupon.id === couponCode)) {
...
}

So I am wondering how this works? I tired reading a few other questions but I don't fully grasp this concept.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

$cart.coupons.length > 0 will return a falsey value if coupons is empty, but there is no need to check length this way in this case. A smaller approach to this flow would be the following:

$cart.coupons?.find(({ id }) => id === couponCode);

If coupons is undefined, undefined is returned.

If no values satisfy the testing function inside find, undefined is returned.

Therefore, no need to test length separately.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!