Detecting an undefined object property

后端 未结 30 2847
花落未央
花落未央 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).

    0 讨论(0)
  • 2020-11-21 05:42

    Going through the comments, for those who want to check both is it undefined or its value is null:

    //Just in JavaScript
    var s; // Undefined
    if (typeof s == "undefined" || s === null){
        alert('either it is undefined or value is null')
    }
    

    If you are using jQuery Library then jQuery.isEmptyObject() will suffice for both cases,

    var s; // Undefined
    jQuery.isEmptyObject(s); // Will return true;
    
    s = null; // Defined as null
    jQuery.isEmptyObject(s); // Will return true;
    
    //Usage
    if (jQuery.isEmptyObject(s)) {
        alert('Either variable:s is undefined or its value is null');
    } else {
         alert('variable:s has value ' + s);
    }
    
    s = 'something'; // Defined with some value
    jQuery.isEmptyObject(s); // Will return false;
    
    0 讨论(0)
  • 2020-11-21 05:42
    function isUnset(inp) {
      return (typeof inp === 'undefined')
    }
    

    Returns false if variable is set, and true if is undefined.

    Then use:

    if (isUnset(var)) {
      // initialize variable here
    }
    
    0 讨论(0)
  • 2020-11-21 05:43

    In JavaScript there is null and there is undefined. They have different meanings.

    • undefined means that the variable value has not been defined; it is not known what the value is.
    • null means that the variable value is defined and set to null (has no value).

    Marijn Haverbeke states, in his free, online book "Eloquent JavaScript" (emphasis mine):

    There is also a similar value, null, whose meaning is 'this value is defined, but it does not have a value'. The difference in meaning between undefined and null is mostly academic, and usually not very interesting. In practical programs, it is often necessary to check whether something 'has a value'. In these cases, the expression something == undefined may be used, because, even though they are not exactly the same value, null == undefined will produce true.

    So, I guess the best way to check if something was undefined would be:

    if (something == undefined)
    

    Object properties should work the same way.

    var person = {
        name: "John",
        age: 28,
        sex: "male"
    };
    
    alert(person.name); // "John"
    alert(person.fakeVariable); // undefined
    
    0 讨论(0)
  • 2020-11-21 05:45

    The solution is incorrect. In JavaScript,

    null == undefined
    

    will return true, because they both are "casted" to a boolean and are false. The correct way would be to check

    if (something === undefined)
    

    which is the identity operator...

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题