If you wish to determine if a global variable or property exists, one way is to use the hasOwnProperty method. For example, window.hasOwnProperty('myVar')
or object.hasOwnProperty('myVar')
will return true if the variable/property has been defined.
The typeof operator alone may not provide accurate information as it will only return 'undefined' for variables that have not been defined at all. To check if a variable is defined but not assigned a value, you can combine it with another technique. However, be aware that this approach may still result in false positives if a variable was initially assigned a value of undefined.
For local variables (non-global), you cannot reference their objects directly. Attempting to call an undefined variable should trigger an exception. You can use the following code snippet to test for this:
function isDefined(variableName) {
try {
eval(variableName);
} catch (ex) {
return false;
}
return true;
}
The use of eval in this function ensures that any exceptions occur within the try-catch block and not when isDefined is called. It is important to note that using this method in production environments is strongly discouraged.
In light of these considerations, it raises the question of whether checking for the existence of a variable is truly necessary in your context.