Detecting an undefined object property

后端 未结 30 2851
花落未央
花落未央 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:49

    What does this mean: "undefined object property"?

    Actually it can mean two quite different things! First, it can mean the property that has never been defined in the object and, second, it can mean the property that has an undefined value. Let's look at this code:

    var o = { a: undefined }
    

    Is o.a undefined? Yes! Its value is undefined. Is o.b undefined? Sure! There is no property 'b' at all! OK, see now how different approaches behave in both situations:

    typeof o.a == 'undefined' // true
    typeof o.b == 'undefined' // true
    o.a === undefined // true
    o.b === undefined // true
    'a' in o // true
    'b' in o // false
    

    We can clearly see that typeof obj.prop == 'undefined' and obj.prop === undefined are equivalent, and they do not distinguish those different situations. And 'prop' in obj can detect the situation when a property hasn't been defined at all and doesn't pay attention to the property value which may be undefined.

    So what to do?

    1) You want to know if a property is undefined by either the first or second meaning (the most typical situation).

    obj.prop === undefined // IMHO, see "final fight" below
    

    2) You want to just know if object has some property and don't care about its value.

    'prop' in obj
    

    Notes:

    • You can't check an object and its property at the same time. For example, this x.a === undefined or this typeof x.a == 'undefined' raises ReferenceError: x is not defined if x is not defined.
    • Variable undefined is a global variable (so actually it is window.undefined in browsers). It has been supported since ECMAScript 1st Edition and since ECMAScript 5 it is read only. So in modern browsers it can't be redefined to true as many authors love to frighten us with, but this is still a true for older browsers.

    Final fight: obj.prop === undefined vs typeof obj.prop == 'undefined'

    Pluses of obj.prop === undefined:

    • It's a bit shorter and looks a bit prettier
    • The JavaScript engine will give you an error if you have misspelled undefined

    Minuses of obj.prop === undefined:

    • undefined can be overridden in old browsers

    Pluses of typeof obj.prop == 'undefined':

    • It is really universal! It works in new and old browsers.

    Minuses of typeof obj.prop == 'undefined':

    • 'undefned' (misspelled) here is just a string constant, so the JavaScript engine can't help you if you have misspelled it like I just did.

    Update (for server-side JavaScript):

    Node.js supports the global variable undefined as global.undefined (it can also be used without the 'global' prefix). I don't know about other implementations of server-side JavaScript.

提交回复
热议问题