0

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

syldman
  • 505
  • 1
  • 6
  • 18
  • 2
    It depends on whether the property can contain falsey values. If the value is `0`, `if (Obj.attr)` will fail while `if ('attr' in Obj)` will succeed. – Barmar Apr 12 '22 at 20:19
  • 1
    If valid values are always truthy (e.g. the property is always an object) then either approach is fine. – Barmar Apr 12 '22 at 20:20
  • 1
    Very similar, but with an unfortunate feature detection focus: https://stackoverflow.com/questions/34605886/property-detection-using-in-versus-trying-to-access-property, https://stackoverflow.com/questions/7174748/javascript-object-detection-dot-syntax-versus-in-keyword – Ry- Apr 12 '22 at 20:23
  • thought about the same, but was wondering if any other considerations – syldman Apr 12 '22 at 20:26

2 Answers2

2

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
Lauren Prete
  • 142
  • 4
1

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)
zeehyt
  • 193
  • 7