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

242
Visualizações
JS: Which approach is better if (object.attr) or if (attr in object)

When checking if attribute exists in an object which approach is better: if (Obj.attr) or if ('attr' in Obj)?

about 4 years ago · Santiago Gelvez
2 Respostas
Responde à pergunta

0

The best thing to use is hasOwnProperty()

hasOwnProperty will check only for those properties that belong to just the object in question and not those inherited (i.e. from its Prototype).

Using 'attr' in Obj will return also those properties that are inherited. Using Obj.attr will get the value of that attribute.

For example, say we have the object:

var obj = { name: "John", age: "32" }

'name' in obj; // returns true
obj.hasOwnProperty("name"); // returns true
obj.name; // returns "John"

'toString' in obj; //returns true
obj.hasOwnProperty("toString"); //returns false
obj.toString; // returns "toString" function defintion from prototype
about 4 years ago · Santiago Gelvez Relatório

0

You must evaluate whether attr can be determined as falsy (null, 0, "", etc). If so then if (Obj.attr) may not trigger with intention to check if the attribute exists.

If you want to check the attribute on the original object, using hasOwnProperty is the most ideal way.

if (Obj.hasOwnProperty('attr')

OR

Check if the attribute is strictly undefined

if (Obj.attr !== undefined)
about 4 years ago · Santiago Gelvez 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