It seems to me that there are four different ways I can determine whether a given object (e.g. foo
) has a given property (e.g. bar
) defined:
There are indeed some subtle differences between the various methods/keywords.
foo.hasOwnProperty('bar')
returns true only if the property 'bar' is defined on the foo object itself. Other properties, such as 'toString' will return false however since they are defined up the prototype chain.
The in
keyword operator returns true if the specified property is in the specified object. Both 'bar' in foo
and 'toString' in foo
would return true.
Since you are checking for the state of the property, the result will be true when bar is not defined on foo and when bar is defined but the value is set to undefined
.