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

139
Views
What is wrong with this way of checking if an object is empty?
function isEmpty(obj) {
  for(var key in obj) {
    return false;
    }
    return true;
}

What is wrong with this way of checking if an object is empty? I'm fairly new to JS and I'm going through SO to check what is the best and fastest way of checking if an object is empty and came across is this How do I test for an empty JavaScript object? among others.

All questions have similar answers checking Object.prototype.hasOwnProperty which seems unnecessarily complicated. Is there a use-case where the code I've provided won't work and I should use the answers provided in the linked questions?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Consider the following case:

const foo = { a: 1 }
const bar = {}
Object.setPrototypeOf(bar, foo)
console.log(bar) // {}
for (let key in bar) console.log(key) // logs a!!

That is what I meant in the comment about walking the prototype chain.

Consider also this:

const foo = {}
Object.defineProperty(foo, 'a', {
  enumerable: false,
  value: 1,
})
console.log(foo.a) // 1
for (let key in foo) console.log(key) // doesn't log anything!

So that's two edge cases your function misses. You probably don't want to log anything in the first example, and you probably do want to log the key in the second.

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!