Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

100
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda