Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
46
rated 0 times [  50] [ 4]  / answers: 1 / hits: 18983  / 13 Years ago, wed, august 24, 2011, 12:00:00

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


More From » properties

 Answers
23

  • 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, 0 etc (which is not what you want).



    var object = {property: 0};
    if(object.isNotSet) { ... } // will not run
    if(object.property) { ... } // will not run

  • 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.



    var object = {property: 0};
    if('property' in object) { ... } // will run
    if('toString' in object) { ... } // will also run; from prototype

  • if(object.hasOwnProperty('property'))



    is even better, since it will allow you to distinguish between instance properties and prototype properties.



    var object = {property: 0};
    if(object.hasOwnProperty('property')) { ... } // will run
    if(object.hasOwnProperty('toString')) { ... } // will not run



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, hasOwnProperty has 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:



function has(obj, prop) {
return Object.prototype.hasOwnProperty.call(obj, prop);
}


Now this works:



has(window, 'setTimeout'); // true


even if window.hasOwnProperty === undefined (which is the case in IE version 8 or lower).


[#90440] Tuesday, August 23, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
havenbilliec

Total Points: 324
Total Questions: 106
Total Answers: 94

Location: Pitcairn Islands
Member since Fri, Oct 15, 2021
3 Years ago
;