Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

99
Views
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 answers
Answer question

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 Report

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!