JavaScript check if variable exists (is defined/initialized)

前端 未结 29 1641
孤城傲影
孤城傲影 2020-11-22 00:59

Which method of checking if a variable has been initialized is better/correct? (Assuming the variable could hold anything (string, int, object, function, etc.))



        
29条回答
  •  耶瑟儿~
    2020-11-22 01:29

    How to check if a variable exists

    This is a pretty bulletproof solution for testing if a variable exists and has been initialized :

    var setOrNot = typeof variable !== typeof undefined;
    

    It is most commonly used in combination with a ternary operator to set a default in case a certain variable has not been initialized :

    var dark = typeof darkColor !== typeof undefined ? darkColor : "black";
    

    Problems with encapsulation

    Unfortunately, you cannot simply encapsulate your check in a function.

    You might think of doing something like this :

    function isset(variable) {
        return typeof variable !== typeof undefined;
    }
    

    However, this will produce a reference error if you're calling eg. isset(foo) and variable foo has not been defined, because you cannot pass along a non-existing variable to a function :

    Uncaught ReferenceError: foo is not defined


    Testing whether function parameters are undefined

    While our isset function cannot be used to test whether a variable exists or not (for reasons explained hereabove), it does allow us to test whether the parameters of a function are undefined :

    var a = '5';
    
    var test = function(x, y) {
        console.log(isset(x));
        console.log(isset(y));
    };
    
    test(a);
    
    // OUTPUT :
    // ------------
    // TRUE
    // FALSE
    

    Even though no value for y is passed along to function test, our isset function works perfectly in this context, because y is known in function test as an undefined value.

提交回复
热议问题