I have seen two ways of detecting whether a UA implements a specific JS property: if(object.property) and if('property' in object).
I would like to hear opinions on which is better, and most importantly, why. Is one unequivocally better than the other? Are there more than just these two ways to do object property detection? Please cover browser support, pitfalls, execution speed, and such like, rather than aesthetics.
Edit: Readers are encouraged to run the tests at jsperf.com/object-detection
if(object.property)will fail in cases it is not set (which is what you want), and in cases it has been set to some falsey value, e.g.
undefined,null,0etc (which is not what you want).if('property' in object)is slightly better, since it will actually return whether the object really has the property, not just by looking at its value.
if(object.hasOwnProperty('property'))is even better, since it will allow you to distinguish between instance properties and prototype properties.
I would say performance is not that big of an issue here, unless you’re checking thousands of time a second but in that case you should consider another code structure. All of these functions/syntaxes are supported by recent browsers,
hasOwnPropertyhas been around for a long time, too.Edit: You can also make a general function to check for existence of a property by passing anything (even things that are not objects) as an object like this:
Now this works:
even if
window.hasOwnProperty === undefined(which is the case in IE version 8 or lower).