How to find out if a variable has been defined
It’s two articles now, it must be a series! Here’s how to find the out if a variable has been defined in my three favorite languages:
/* v has not been declared */ if (isset($v)) echo "v has been defined"; else echo "v has _not_ been defined";
As an example: “window.doesnotexist==null” results in true. Be careful not to overwrite stuff that already does exist in the window.
/* v has not been declared */ if (window.v) alert("v has been defined"); else alert("v has _not_ been defined");
In Visual Basic you will only be able to use this code if “option explicit” is off, meaning in VBScript, VBA and VB6.0 there should not be a line on the top which says “Option Explicit”. In the .NET environment there is a setting for this in the options dialog (project properties). In the case Option Explicit is on, variables will always be assigned a default value, so you can never check e.g. if an integer variable has been assigned a value of 0.
You can either check using the typename function or using the isEmpty function.
As an example: Debug.Print TypeName(doesnotexist)=”Empty” shows True
if isempty(v) then debug.print "v has been defined" else debug.print "v has _not_ been defined" end if