Sunday, April 8, 2012

JavaScript: Is a member defined?



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:







  1. if (foo.hasOwnProperty(bar)) {





  2. if ('bar' in foo) {





  3. if (typeof foo.bar !== 'undefined') {





  4. 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?



Source: Tips4all

4 comments:

  1. No they are totally different. Example:

    foo = {bar: undefined};
    Object.prototype.baz = undefined;
    Object.prototype.bing = "hello";


    Then:

    (typeof foo.bar != "undefined") === false
    ('bar' in foo) === true
    (foo.hasOwnProperty('bar')) === true


    (typeof foo.baz != "undefined") === false
    ('baz' in foo) === true
    (foo.hasOwnProperty('baz')) === false


    (typeof foo.bing != "undefined") === true
    ('bing' in foo) === true
    (foo.hasOwnProperty('bing')) === false


    Logic-wise:


    foo.hasOwnProperty('bar') implies 'bar' in foo
    typeof foo.bar != "undefined" implies 'bar' in foo
    But those are the only inferences you can draw; no other implications are universally true, as the above counterexamples show.

    ReplyDelete
  2. 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.

    ReplyDelete
  3. 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.

    ReplyDelete
  4. 'bar' in foo


    will look anywhere up the prototype chain. Testing to see if foo.bar !== undefined will also return true if bar is anywhere in foo'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 of foo.

    Per MDN


    Every object descended from Object inherits the hasOwnProperty method.
    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.

    ReplyDelete