简体   繁体   中英

Best way to check if a variable exists in Javascript?

Well, my question is obvious,

Example:

Define a with default value undefined :

var a;

If I want to check if a var exists, I will try with:

But in this case, a does exists and a value is undefined , but in the boolean evaluation this is false .

 var a; // default value is 'undefined' if (a) { alert('a exists'); } else { alert("a don't exists") } 

I can also try with the following example: but this example generates a error.

 // var a; // a is not defined if (a) { alert('a exists'); } else { alert("a don't exists") } 

And in this example, I try with typeof . But a is defined with undefined value by default.

 var a; if (typeof a != 'undefined') { alert('a exists'); } else { alert("a don't exists") } 

And in this example

 console.log ('var a exists:', window.hasOwnProperty('a')); 

What is the best way to verify if a variable actually exists and why?

Thanks.

There are three different possibilities in JS for a variable.

  1. Variable 'a' not at all declared;
  2. Variable 'a' declared, but unassigned (undefined). Ex: var a;
  3. Variable 'a' declared, but assigned with empty or null. (Possible scenario, if a variable trying to get value from back-end)
    Ex: var a=null; var a=''; var a=null; var a='';

If you are expecting a value in variable, other than 0 or false, then better to use following condition. And of course its all based on your need and if you unsure about variable or object values, always enclose them in try & catch block.

 //var a; //var a=null; //var a=''; //var a=0; //var a='value'; if (typeof a != "undefined" && a) { alert("a is defined AND a is TRUE value"); } else { alert("a not exist OR a is a FALSE value"); } 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM