Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

146
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda