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

169
Vistas
Optioning chaining not working for array.length === x

let products;

if (products?.length !== 0) {
  console.log('true')
}

vs

let products;

if (products && products.length !== 0) {
  console.log('true')
}

If there is no product array, example 1 will still run the if statement. Shouldn't the optional chaining check to see if product exists, then check for the length and finally check length to 0?

Example. 2 will not run if product does not exist.

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

Optional chaining does not take precedence over comparison. This

if (products?.length !== 0) {

is

if ((products?.length) !== 0) {

It evaluates the chain, then compares the result to 0. If there was a value at the end of the chain, that'll be compared. If the chain failed due to something being nullish, it'll evaluate to undefined, and that will be compared with 0.

if ((undefined) !== 0) {

which will always be true.

Since you want the block to run if products exists and isn't empty, use

if (products?.length) {
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