Detecting an undefined object property

后端 未结 30 2839
花落未央
花落未央 2020-11-21 04:43

What\'s the best way of checking if an object property in JavaScript is undefined?

30条回答
  •  情歌与酒
    2020-11-21 05:42

    The issue boils down to three cases:

    1. The object has the property and its value is not undefined.
    2. The object has the property and its value is undefined.
    3. The object does not have the property.

    This tells us something I consider important:

    There is a difference between an undefined member and a defined member with an undefined value.

    But unhappily typeof obj.foo does not tell us which of the three cases we have. However we can combine this with "foo" in obj to distinguish the cases.

                                   |  typeof obj.x === 'undefined' | !("x" in obj)
    1.                     { x:1 } |  false                        | false
    2.    { x : (function(){})() } |  true                         | false
    3.                          {} |  true                         | true
    

    Its worth noting that these tests are the same for null entries too

                                   |  typeof obj.x === 'undefined' | !("x" in obj)
                        { x:null } |  false                        | false
    

    I'd argue that in some cases it makes more sense (and is clearer) to check whether the property is there, than checking whether it is undefined, and the only case where this check will be different is case 2, the rare case of an actual entry in the object with an undefined value.

    For example: I've just been refactoring a bunch of code that had a bunch of checks whether an object had a given property.

    if( typeof blob.x != 'undefined' ) {  fn(blob.x); }
    

    Which was clearer when written without a check for undefined.

    if( "x" in blob ) { fn(blob.x); }
    

    But as has been mentioned these are not exactly the same (but are more than good enough for my needs).

提交回复
热议问题