How to check if array is empty?

Advertisements

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

>Solution :

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

You could simply do this:

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

Leave a ReplyCancel reply