How to check if object property exists with a variable holding the property name?

Slopeside Creative picture Slopeside Creative · Jun 14, 2012 · Viewed 706.7k times · Source

I am checking for the existence of an object property with a variable holding the property name in question.

var myObj;
myObj.prop = "exists";
var myProp = "p"+"r"+"o"+"p";

if(myObj.myProp){
    alert("yes, i have that property");
};

This is undefined because it's looking for myObj.myProp but I want it to check for myObj.prop

Answer

Rocket Hazmat picture Rocket Hazmat · Jun 14, 2012
var myProp = 'prop';
if(myObj.hasOwnProperty(myProp)){
    alert("yes, i have that property");
}

Or

var myProp = 'prop';
if(myProp in myObj){
    alert("yes, i have that property");
}

Or

if('prop' in myObj){
    alert("yes, i have that property");
}

Note that hasOwnProperty doesn't check for inherited properties, whereas in does. For example 'constructor' in myObj is true, but myObj.hasOwnProperty('constructor') is not.