How to check a not-defined variable in JavaScript

后端 未结 14 743
陌清茗
陌清茗 2020-11-22 14:23

I wanted to check whether the variable is defined or not. For example, the following throws a not-defined error

alert( x );

How can I cat

相关标签:
14条回答
  • 2020-11-22 15:09

    You can also use the ternary conditional-operator:

    var a = "hallo world";
    var a = !a ? document.write("i dont know 'a'") : document.write("a = " + a);

    //var a = "hallo world";
    var a = !a ? document.write("i dont know 'a'") : document.write("a = " + a);

    0 讨论(0)
  • 2020-11-22 15:09

    I often use the simplest way:

    var variable;
    if (variable === undefined){
        console.log('Variable is undefined');
    } else {
        console.log('Variable is defined');
    }
    

    EDIT:

    Without initializing the variable, exception will be thrown "Uncaught ReferenceError: variable is not defined..."

    0 讨论(0)
  • 2020-11-22 15:14

    Technically, the proper solution is (I believe):

    typeof x === "undefined"
    

    You can sometimes get lazy and use

    x == null
    

    but that allows both an undefined variable x, and a variable x containing null, to return true.

    0 讨论(0)
  • 2020-11-22 15:14

    An even easier and more shorthand version would be:

    if (!x) {
       //Undefined
    }
    

    OR

    if (typeof x !== "undefined") {
        //Do something since x is defined.
    }
    
    0 讨论(0)
  • 2020-11-22 15:15

    I use a small function to verify a variable has been declared, which really cuts down on the amount of clutter in my javascript files. I add a check for the value to make sure that the variable not only exists, but has also been assigned a value. The second condition checks whether the variable has also been instantiated, because if the variable has been defined but not instantiated (see example below), it will still throw an error if you try to reference it's value in your code.

    Not instantiated - var my_variable; Instantiated - var my_variable = "";

    function varExists(el) { 
      if ( typeof el !== "undefined" && typeof el.val() !== "undefined" ) { 
        return true; 
      } else { 
        return false; 
      } 
    }
    

    You can then use a conditional statement to test that the variable has been both defined AND instantiated like this...

    if ( varExists(variable_name) ) { // checks that it DOES exist } 
    

    or to test that it hasn't been defined and instantiated use...

    if( !varExists(variable_name) ) { // checks that it DOESN'T exist }
    
    0 讨论(0)
  • 2020-11-22 15:18

    Another potential "solution" is to use the window object. It avoids the reference error problem when in a browser.

    if (window.x) {
        alert('x exists and is truthy');
    } else {
        alert('x does not exist, or exists and is falsy');
    }
    
    0 讨论(0)
提交回复
热议问题