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

4 Answers 4

4

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

You could simply do this:

{ar2.length === 0 && 'This is empty'}
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

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

1 Comment

Use === instead of ==
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

2 Comments

No need to use ar2 !== undefined, This check is redundant because Array.isArray(ar2) will return false if it is not an array.
@decpk thankyou for the correction.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.