JavaScript check if variable exists (is defined/initialized)

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

    To check if a variable has been declared/set I did this dirty trick.

    I haven't found a way to extract the code to a function, even with eval.

    "use strict";
    
    // var someVar;
    
    var declared;
    try {
      someVar;
      declared = true;
    } catch(e) {
      declared = false;
    }
    
    if (declared) {
      console.log("someVar is declared; now has the value: " + someVar);
    } else {
      console.log("someVar is not declared");
    }
    
    0 讨论(0)
  • 2020-11-22 01:23

    Short way to test a variable is not declared (not undefined) is

    if (typeof variable === "undefined") {
      ...
    }
    

    I found it useful for detecting script running outside a browser (not having declared window variable).

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

    The highest answer is correct, use typeof.

    However, what I wanted to point out was that in JavaScript undefined is mutable (for some ungodly reason). So simply doing a check for varName !== undefined has the potential to not always return as you expect it to, because other libs could have changed undefined. A few answers (@skalee's, for one), seem to prefer not using typeof, and that could get one into trouble.

    The "old" way to handle this was declaring undefined as a var to offset any potential muting/over-riding of undefined. However, the best way is still to use typeof because it will ignore any overriding of undefined from other code. Especially if you are writing code for use in the wild where who knows what else could be running on the page...

    0 讨论(0)
  • 2020-11-22 01:23
    if (typeof console != "undefined") {    
       ...
    }
    

    Or better

    if ((typeof console == "object") && (typeof console.profile == "function")) {    
       console.profile(f.constructor);    
    }
    

    Works in all browsers

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

    You can also use !! before a variable to check if it's defined. E.g.

    let dog = "woof";
    let chineseCat; // Undefined.
    console.log("1.");
    console.log(!!dog && !!chineseCat ? "Both are defined" : "Both are NOT defined");
    
    chineseCat= "mao"; // dog and chineseCat are now defined.
    console.log("2.");
    console.log(!!dog && !!chineseCat ? "Both are defined" : "Both are NOT defined");
    

    Output:

    1.
    Both are NOT defined
    2. 
    Both are defined
    
    0 讨论(0)
  • 2020-11-22 01:24

    My preference is typeof(elem) != 'undefined' && elem != null.

    However you choose, consider putting the check in a function like so

    function existy (x) {
        return typeof (x) != 'undefined' && x != null;
    }
    

    If you don't know the variable is declared then continue with typeof (x) != 'undefined' && x != null;

    Where you know the variable is declared but may not be existy, you could use

    existy(elem) && doSomething(elem);
    

    The variable you are checking may be a nested property sometimes. You can use prop || {} to go down the line checking existance to the property in question:

    var exists = ((((existy(myObj).prop1||{}).prop2||{}).prop3||{})[1]||{}).prop4;
    

    After each property use (...' || {}').nextProp so that a missing property won't throw an error.

    Or you could use existy like existy(o) && existy(o.p) && existy(o.p.q) && doSomething(o.p.q)

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