Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

223
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda