Detecting an undefined object property

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

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

30条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-21 05:41

    Simply anything is not defined in JavaScript, is undefined, doesn't matter if it's a property inside an Object/Array or as just a simple variable...

    JavaScript has typeof which make it very easy to detect an undefined variable.

    Simply check if typeof whatever === 'undefined' and it will return a boolean.

    That's how the famous function isUndefined() in AngularJs v.1x is written:

    function isUndefined(value) {return typeof value === 'undefined';} 
    

    So as you see the function receive a value, if that value is defined, it will return false, otherwise for undefined values, return true.

    So let's have a look what gonna be the results when we passing values, including object properties like below, this is the list of variables we have:

    var stackoverflow = {};
    stackoverflow.javascipt = 'javascript';
    var today;
    var self = this;
    var num = 8;
    var list = [1, 2, 3, 4, 5];
    var y = null;
    

    and we check them as below, you can see the results in front of them as a comment:

    isUndefined(stackoverflow); //false
    isUndefined(stackoverflow.javascipt); //false
    isUndefined(today); //true
    isUndefined(self); //false
    isUndefined(num); //false
    isUndefined(list); //false
    isUndefined(y); //false
    isUndefined(stackoverflow.java); //true
    isUndefined(stackoverflow.php); //true
    isUndefined(stackoverflow && stackoverflow.css); //true
    

    As you see we can check anything with using something like this in our code, as mentioned you can simply use typeof in your code, but if you are using it over and over, create a function like the angular sample which I share and keep reusing as following DRY code pattern.

    Also one more thing, for checking property on an object in a real application which you not sure even the object exists or not, check if the object exists first.

    If you check a property on an object and the object doesn't exist, will throw an error and stop the whole application running.

    isUndefined(x.css);
    VM808:2 Uncaught ReferenceError: x is not defined(…)
    

    So simple you can wrap inside an if statement like below:

    if(typeof x !== 'undefined') {
      //do something
    }
    

    Which also equal to isDefined in Angular 1.x...

    function isDefined(value) {return typeof value !== 'undefined';}
    

    Also other javascript frameworks like underscore has similar defining check, but I recommend you use typeof if you already not using any frameworks.

    I also add this section from MDN which has got useful information about typeof, undefined and void(0).

    Strict equality and undefined
    You can use undefined and the strict equality and inequality operators to determine whether a variable has a value. In the following code, the variable x is not defined, and the if statement evaluates to true.

    var x;
    if (x === undefined) {
       // these statements execute
    }
    else {
       // these statements do not execute
    }
    

    Note: The strict equality operator rather than the standard equality operator must be used here, because x == undefined also checks whether x is null, while strict equality doesn't. null is not equivalent to undefined. See comparison operators for details.


    Typeof operator and undefined
    Alternatively, typeof can be used:

    var x;
    if (typeof x === 'undefined') {
       // these statements execute
    }
    

    One reason to use typeof is that it does not throw an error if the variable has not been declared.

    // x has not been declared before
    if (typeof x === 'undefined') { // evaluates to true without errors
       // these statements execute
    }
    
    if (x === undefined) { // throws a ReferenceError
    
    }
    

    However, this kind of technique should be avoided. JavaScript is a statically scoped language, so knowing if a variable is declared can be read by seeing whether it is declared in an enclosing context. The only exception is the global scope, but the global scope is bound to the global object, so checking the existence of a variable in the global context can be done by checking the existence of a property on the global object (using the in operator, for instance).


    Void operator and undefined

    The void operator is a third alternative.

    var x;
    if (x === void 0) {
       // these statements execute
    }
    
    // y has not been declared before
    if (y === void 0) {
       // throws a ReferenceError (in contrast to `typeof`)
    }
    

    more > here

提交回复
热议问题