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.
hasOwnProperty
is exactly what you're looking for, since you specify "if the property is explicitly defined for this object, not in the prototype chain". Per https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Object/hasOwnProperty , "This method can be used to determine whether an object has the specified property as a direct property of that object; unlike the in operator, this method does not check down the object's prototype chain." -- seems to exactly match your requirement!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With