Use Option Explicit

Homepage > ASP Tutorials > Use Option Explicit

I can't stress the importance of using Option Explicit strongly enough. Many ASP developers either forget or don't bother to do this and it creates all sorts of problems once the code starts building up.

So why is it so important? Take a look at this example:

<%
  sPageName = "somepage.asp"
  response.write sPagName
%>

Notice the misspelling of sPageName on the second line. Because of this the server automatically creates a new variable (sPagName) as a blank string and since we haven't used Option Explicit, this error goes un-noticed.

This is easy to spot here, but imagine if this were buried in hundreds of lines of code. Worse still, this variable could be part of a complex calculation and you could end up spend hours trawling your code trying to figure out why it isn't working (I learnt this the hard way!).

When you use Option Explicit it must be the first line of your ASP script:

<%
  Option Explicit

  dim sPageName
  sPageName = "somepage.asp"
  response.write sPagName
%>

Now we have to declare (create) our own variables using Dim sVariableName. The server now only allows the use of variables that have already been declared, so now our mis-spelt variable will bring everything to a halt with this error:

Microsoft VBScript runtime (0x800A01F4)
Variable is undefined: 'sPagName'
/asp/myscript.asp, line 6

This let's us know exactly where the error is, so we can go straight to the problem and fix it.

I recently took on some work debugging an website for a financial broker. Their previous developer had completed most of the work then vanished before completing the job properly. The site consisted of about 400 ASP files, the majority of them being tools for controlling monthly figures uploaded by agents.

The application was littered with undeclared variables and the result of this was that some dates were being passed as blank values when the database was edited. This was completely messing up their reports and took quite some time to debug the whole application.

As if this wasn't enough reason to explicitly declare your variables, it turns out that declared variables are accessed quicker than undeclared variables.

Rate this tutorial!

  • Currently 2.8/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Rated 2.8/5 stars (820 votes cast)

Make an enquiry

Privacy policy