Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

237
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!