JavaScript check if variable exists (is defined/initialized)

前端 未结 29 1200
孤城傲影
孤城傲影 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:41
    if (variable === undefined) {}
    

    works just fine, and only checks for undefined.

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

    You could use a try...catch block like the following:

    var status = 'Variable exists'
    
    try {
      myVar
    } catch (ReferenceError) {
      status = 'Variable does not exist'
    }
    
    console.log(status)

    A disadvantage is you cannot put it in a function as it would throw a ReferenceError

    function variableExists(x) {
      var status = true
      try {
        x
      } catch (ReferenceError) {
        status = false
      }
      
      return status
    }
    
    console.log(variableExists(x))

    Edit:

    If you were working in front-end Javascript and you needed to check if a variable was not initialized (var x = undefined would count as not initialized), you could use:

    function globalVariableExists(variable) {
      if (window[variable] != undefined) {
        return true
      }
      
      return false
    }
    
    var x = undefined
    
    console.log(globalVariableExists("x"))
    
    console.log(globalVariableExists("y"))
    
    var z = 123
    
    console.log(globalVariableExists("z"))

    Edit 2:

    If you needed to check if a variable existed in the current scope, you could simply pass this to the function, along with the name of the variable contained in a string:

    function variableExists(variable, thisObj) {
      if (thisObj[variable] !== undefined) {
        return true
      }
      
      return false
    }
    
    class someClass {
      constructor(name) { 
        this.x = 99
        this.y = 99
        this.z = 99
        this.v = 99
        
        console.log(variableExists(name, this))
      }
    }
    
    new someClass('x')
    new someClass('y')
    new someClass('z')
    new someClass('v')
    new someClass('doesNotExist')

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

    In the particular situation outlined in the question,

    typeof window.console === "undefined"
    

    is identical to

    window.console === undefined
    

    I prefer the latter since it's shorter.

    Please note that we look up for console only in global scope (which is a window object in all browsers). In this particular situation it's desirable. We don't want console defined elsewhere.

    @BrianKelley in his great answer explains technical details. I've only added lacking conclusion and digested it into something easier to read.

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

    It depends on the situation. If you're checking for something that may or may not have been defined globally outside your code (like jQuery perhaps) you want:

    if (typeof(jQuery) != "undefined")
    

    (No need for strict equality there, typeof always returns a string.) But if you have arguments to a function that may or may not have been passed, they'll always be defined, but null if omitted.

    function sayHello(name) {
        if (name) return "Hello, " + name;
        else return "Hello unknown person";
    }
    sayHello(); // => "Hello unknown person"
    
    0 讨论(0)
  • 2020-11-22 01:47

    There is another short hand way to check this, when you perform simple assignments and related checks. Simply use Conditional (Ternary) Operator.

    var values = typeof variable !== 'undefined' ? variable : '';
    

    Also this will be helpful, when you try to declare the Global variable with instance assignment of the reference variable.

    If you wanted to check variable shouldn't be undefined or null. Then perform below check.

    When the variable is declared, and if you want to check the value, this is even Simple: and it would perform undefined and null checks together.

    var values = variable ? variable : '';
    
    0 讨论(0)
提交回复
热议问题