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

104
Vistas
How to check if array is empty?

I have this codes below and how can I check if the ar is empty?

  let ar2 = [];
  const items = users[0]?.[2]?.itemList;
  if (items) {
    for (const [key, value] of Object.entries(items)) {
      ar2.push(key, <br />);
    }
  }

if I'll console.log(ar2), it shows this [ ]

How can I check it the array is empty and then display the message "This is empty"?

I tried this but it's not working correctly. Even if it's greater than or less than 0, it will always display "2"

 {ar2 < 0 ? <>1</> : <>2</>}
about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

ar2.length will show you the number of elements in the array.

You could simply do this:

{ar2.length === 0 && 'This is empty'}
about 4 years ago · Juan Pablo Isaza Denunciar

0

You can first check if it is an array and then you can check for the emptiness using length property

1) You can first check whether the ar2 is an array or not using static isArray function. Because you can create an object which has length property but it may or may not be an array

function isEmptyNotRecommended(obj) {
  return obj.length === 0;
}

function isEmptyRecommended(obj) {
  return Array.isArray(obj) && obj.length === 0;
}

const arr = { length: 0 };
// This is not an array but still returns true
console.log(isEmptyNotRecommended(arr));  

// This should be recommended approach to check for array emptiness
console.log(isEmptyRecommended(arr));

RECOMMENDED SOLUTION ⬇

2) If it is an array then It is safe to use length property on it. If its length is more than 0 then it is not empty else it is empty

You can either use ar2.length === 0 or !ar2.length

{
  Array.isArray(ar2) && !ar2.length ? <>1</> : <>2</>;
}
about 4 years ago · Juan Pablo Isaza Denunciar

0

The length property will return the number of items in the array.

If you want to check whether an array is empty, check whether it's length property is 0.

{ar2.length == 0 ? <>1</> : <>2</>}
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