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:

PHP

/* v has not been declared */
if (isset($v))
  echo "v has been defined";
else
  echo "v has _not_ been defined";

JavaScript

Please note that in javascript a runtime error would be generated when trying to access a variable that has not been defined. However, any variable that you create will automatically become a property of the window object. Therefor, checking if the variable has been added to the scope of window will result in a condition that can be checked. Also note that this will only work in a browser, which of course is how most people experience javascript anyway.

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");

(Visual) Basic

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
Advertisements

4 thoughts on “How to find out if a variable has been defined

  1. Your JavaScript isn’t quite right. It’s perfectly legitimate to assign null to a variable:

    v = null

    This makes it defined and then makes it okay to use, but your «if(window.v)» test will still print “v has _not_ been defined”. Ditto if we assign false to v (or 0, or the empty string). Better is to use «if(window.v === undefined)» (note the triple equals). But even that doesn’t catch the case where we assign undefined to a variable. We can’t distinguish between an undefined variable and a variable whose value is undefined.

    We can use a exception handler though:

    try { v; alert(‘defined’) } catch(_) { alert(‘undefined’) }

    which seems kinda sneaky to me.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s