Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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"?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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</>}

>Solution :

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

You could simply do this:

{ar2.length === 0 && 'This is empty'}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading