Home > Software design >  JS: Which approach is better if (object.attr) or if (attr in object)
JS: Which approach is better if (object.attr) or if (attr in object)

Time:04-13

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

CodePudding user response:

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

CodePudding user response:

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)
  • Related