DEV Community

Mehul Lakhanpal
Mehul Lakhanpal

Posted on

Check if a property exists in an object

Alt Text

Top comments (3)

Collapse
 
frondor profile image
Federico Vázquez • Edited

Depends on what you need, but I'd say

({test: undefined}).hasOwnProperty('test')

is better.

They don't produce the same result, since the in operator is going to search for that property in the entire prototype chain, while hasOwnProperty is going to look for that prop only in the context of that object.

Collapse
 
ml318097 profile image
Mehul Lakhanpal • Edited

Nice I didn't know that 'in looks up the chain. Good to know :)

Collapse
 
frondor profile image
Federico Vázquez

You're right. I assumed in was slower simply because it has to iterate many levels, but looks like currently V8 knows how to properly optimize the loop. Thanks for pointing out, I'll edit that part.