-1

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.

Coralee
  • 25
  • 5
  • "`$cart.coupons.length > 0` would return a falsey value" - for what input? I'd get rid of the check altogether since `$cart.coupons.find((coupon) => coupon.id === couponCode)` will already be falsey if `$cart.coupons` is `[]`. – Luatic Jul 12 '22 at 10:36
  • "I got a comment from another add a condition to check if array is undefined and to check if array is in fact an array." - TBH this recommendation seems smelly to me. Is this server code validating user input, or is this client code? Validation should ideally be separated from logic. Anyways, *whether* such checks are reasonable depends on the context and is a better fit for https://codereview.stackexchange.com since it is largely opinion-based. – Luatic Jul 12 '22 at 10:37
  • 2
    `array.length > 0` isn't just false-y; it's a comparison, it's actually `false`, if the array is empty. `0` _is_ false-y, hence so is `array.length` if the array is empty. `array?.length` [optional chaining](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining) is only useful if `array` might be `null` or `undefined` (in which case it would evaluate to `undefined`, also false-y). – jonrsharpe Jul 12 '22 at 10:37

1 Answers1

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.

mdmundo
  • 1,988
  • 2
  • 23
  • 37