Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

252
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda