0

Is it possible to tell whether an inherited object property was set to be undefined or doesn't exist at all?

I have a formatting string with a property name in it, and an object that's expected to contain the property. I don't care if the property is the object's own or inherited, I need to know if it exists at all so I can use it, even if it was set as undefined, but if it doesn't exist at all, I need to throw an error.

I know just how many times this subject has been danced around, and with so many opinions about using:

if(prop in obj){
}

and this one:

obj.hasOwnProperty(prop)

And while I clearly cannot use the second one, the first method seems unreliable when it comes to all possible property values.

Is there a reliable way to check if a particular property exists either within object or inherited, even if its value was set to 0 or null or undefined?

vitaly-t
  • 24,279
  • 15
  • 116
  • 138
  • 2
    *The first method seems unreliable when it comes to all possible property values.* What makes you think so? `var foo = { bar: undefined }; "bar" in foo => true` – Frédéric Hamidi Apr 03 '15 at 12:38
  • Many comments in this question: http://stackoverflow.com/questions/11040472/check-if-object-property-exists-using-a-variable – vitaly-t Apr 03 '15 at 12:43
  • The only relevant and correct comment that I could find is the one that says `in` does not work with strings. Are you sure that's a concern in your use case? – Frédéric Hamidi Apr 03 '15 at 12:46
  • Well, my property name is a string variable, so perhaps yes, if that's what they meant in the comment. – vitaly-t Apr 03 '15 at 12:49
  • `var o = {s: "foo"}; 's' in o => true` – Matt Browne Apr 03 '15 at 12:51
  • @vitaly, their comment says that `var foo = "foo"; "length" in foo => Exception` – Frédéric Hamidi Apr 03 '15 at 12:53
  • The only reason I can think of why `in` by itself might not be sufficient is if you don't want it to return true for properties that belong to the base `Object.prototype`. In that case you can just check `(prop in obj && !(prop in Object.prototype))` – Matt Browne Apr 03 '15 at 12:53
  • 1
    ..with regard to the comment @FrédéricHamidi mentioned, that's because string literals are sort of quasi-objects. If you explicitly made a String object then it would work: `var foo = new String("foo"); "length" in foo` works. – Matt Browne Apr 03 '15 at 12:55

1 Answers1

3

if(prop in obj) seems unreliable when it comes to all possible property values.

No. The in operator does not care about the values at all, it checks only for the property name. It's exactly what you want.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375