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:
if (foo.hasOwnProperty(bar)) {
if ('bar' in foo) {
if (typeof foo.bar !== 'undefined') {
if (foo.bar === undefined) {
To determine if there is a property named "bar
" in the object foo
, are all three of those statements equivalent? Are there any sublte semantics I don't know that makes any of these three statements different?
one difference is that, method 1 will check only foo object for property bar while the last two methods will also check the prototype for inherited property.
will look anywhere up the prototype chain. Testing to see if
foo.bar
!==undefined
will also return true ifbar
is anywhere infoo
's prototype chain, but remember if bar is defined on foo, and set to undefined, this will return false.hasOwnProperty is more choosy - it will only return true is
bar
is defined as a direct property offoo
.Per MDN
These are all different:
foo.hasOwnProperty('bar')
tells you whetherfoo
has the property and does not perform lookup along the prototype chain.'bar' in foo
checks the prototype chain and returns true when it finds propertybar
in any object along the chain.typeof foo.bar != 'undefined'
returns true iffoo
or any object along its prototype chain has propertybar
and it's value is notundefined
.Here is an example that demonstrates these differences:
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
.To add to what others have said, if you just want to know if a property exists and has a non-falsey value (not
undefined
,null
,false
,0
,""
,NaN
, etc...), you can just do this:As long as falsey values are not interesting to you for your particular circumstance, this shortcut will tell you if the variable has been set to something useful for you or not.
If you want to know if the property exists on the object in any way, I find this the most useful, brief and readable:
One can also use something similar on function arguments (again as long as a falsey value isn't something you care about):
No they are totally different. Example:
Then:
Logic-wise:
foo.hasOwnProperty('bar')
implies'bar' in foo
typeof foo.bar != "undefined"
implies'bar' in foo