-2

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</>}
JS3
  • 1,623
  • 3
  • 23
  • 52
  • 1
    you can use `ar.length === 0` to check it. If `ar.length === 0` is `true` then it is empty else it has some content in it. Refer: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/length – Sumit Surana Nov 07 '21 at 04:13
  • 1
    Does this answer your question? [How to check if array is empty or does not exist?](https://stackoverflow.com/questions/24403732/how-to-check-if-array-is-empty-or-does-not-exist) – TBA Nov 07 '21 at 04:14

4 Answers4

4

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

You could simply do this:

{ar2.length === 0 && 'This is empty'}
mountman
  • 56
  • 1
4

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</>;
}
DecPK
  • 24,537
  • 6
  • 26
  • 42
2

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</>}
Spectric
  • 30,714
  • 6
  • 20
  • 43
0

You should follow this step:

  • if ar is undefined?
  • if ar is array
  • if ar is empty

all of that, you would have this condition:

ar2 !== undefined && Array.isArray(ar2) && ar2.length > 0