JavaScript check if variable exists (is defined/initialized)

前端 未结 29 1150
孤城傲影
孤城傲影 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:25

    You want the typeof operator. Specifically:

    if (typeof variable !== 'undefined') {
        // the variable is defined
    }
    
    0 讨论(0)
  • 2020-11-22 01:27

    you can use the typeof operator.

    For example,

    var dataSet;
    
    alert("Variable dataSet is : " + typeof dataSet);
    

    Above code snippet will return the output like

    variable dataSet is : undefined.

    0 讨论(0)
  • 2020-11-22 01:27

    In ReactJS, things are a bit more complicated! This is because it is a compiled environment, which follows ESLint's no-undef rule since react-scripts@2.0.3 (released Oct. 1st, 2018). The documentation here is helpful to anyone interested in this problem...

    In JavaScript, prior to ES6, variable and function declarations are hoisted to the top of a scope, so it's possible to use identifiers before their formal declarations in code....

    This [new] rule [of ES6] will warn when it encounters a reference to an identifier that has not yet been declared.

    So, while it's possible to have an undefined (or "uninitialized") variable, it is not possible to have an undeclared variable in ReactJS without turning off the eslint rules.

    This can be very frustrating -- there are so many projects on GitHub that simply take advantage of the pre-ES6 standards; and directly compiling these without any adjustments is basically impossible.

    But, for ReactJS, you can use eval(). If you have an undeclared variable like...

    if(undeclaredvar) {...}
    

    You can simply rewrite this part as...

    if(eval('typeof undeclaredvar !== "undefined"')) {...}
    

    For instance...

    if(eval("false")) {
      console.log("NO!");
    }
    if(eval("true")) {
      console.log("YEAH!");
    }

    For those importing GitHub repositories into a ReactJS project, this is simply the only way to check if a variable is declared. Before closing, I'd like to remind you that there are security issues with eval() if use incorrectly.

    0 讨论(0)
  • 2020-11-22 01:28

    It is difficult to distinguish between undefined and null. Null is a value you can assign to a variable when you want to indicate that the variable has no particular value. Undefined is a special value which will be the default value of unassigned variables.

    
    var _undefined;
    var _null = null;
    
    alert(_undefined); 
    alert(_null); 
    alert(_undefined == _null);
    alert(_undefined === _null);
    
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-11-22 01:31

    It depends if you just care that the variable has been defined or if you want it to have a meaningful value.

    Checking if the type is undefined will check if the variable has been defined yet.

    === null or !== null will only check if the value of the variable is exactly null.

    == null or != null will check if the value is undefined or null.

    if(value) will check if the variable is undefined, null, 0, or an empty string.

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