JavaScript check if variable exists (is defined/initialized)

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

提交回复
热议问题