Alex Rivera | Logout

What's the correct way to test for existence of a property on a JavaScript Object?

Asked 2009-05-22T04:11:50.737
26

I have a custom Javascript object that I create with new, and assign properties to based on creation arguments:

function MyObject(argument) {
    if (argument) {
        this.prop = "foo";
    }
}
var objWithProp = new MyObject(true); // objWithProp.prop exists
var objWithoutProp = new MyObject(false); // objWithoutProp.prop does not exist

What's the correct way to test for the existence of the prop property of the objects? I've seen the following ways used, but I'm not sure if any of these ways is the best way:

  • if (obj.prop) {}
  • if (obj.hasOwnProperty("prop")) {}
  • if ("prop" in obj) {}

Specifically, I'm only interested in testing if the property is explicitly defined for this object, not in the prototype chain. In addition, the value will never be set to null or undefined, but it could be something like an empty object or array. However, if you want to include what the correct way is if those could be the case, feel free.

Edit
Report

1 Answer

10

If you are looking for a property defined in an object, you can use hasOwnProperty method of the object. like this:

myObject = new MyObject();
// some code
if ( myObject.hasOwnProperty('prop') ) {
    // prop exists
}

but this is only to know if such a property is defined in object itself, but not its parents. so if such property is inherited by the object, you can not test its existence like this.

the other way is to test the property against undefined value. like this:

if ( myObject.prop !== undefined ) {
    // prop exists
}

remember to use the !== operator instead of != because != will not differ between null and undefined, but !== does. so if your object has a property but the value is null, != will not help you. so this test:

if ( myObject.prop ) {
}

might have wrong results if "prop" has a false or null value. but by comparing to undefined with !== operator, you can be sure that null/false values will not confuse you.

answered 2009-05-22T06:01:42.260

Your Answer