The VBScript Network and Systems Administrator's Cafe

May 26 2008   3:48PM GMT

VBScript Statements: Explanation of the Option Explicit Statement



Posted by: Jerry Lees
VBScript, VBScript Statements, vbscriptstatements, option explicit, option

In VBScript declaring your variables up front is not required (as stated in this sites explanation of the Dim Statement), however, many programmers choose to declare their variables up front to avoid having to track down misspellings in their code. They go further by adding the Option Explicit statement to force them to do so. With Option Explicit turned on and error is thrown when a variable is used before being declared.

Consider the following code, that doesn’t use Option Explicit:

TheFirstVariable = 1
TheSecondVariable = 2
TheThirdVariable = TehFirstVariable + TheSecondVariable

Wscript.echo TheThirdVariable

The output will be 2, when you were expecting 3! To find the error, if you didn’t notice it, read the third line very slowly TheFirstVariable is spelled differently as TehFirstVariable– therefore creating a new variable with a default value of zero. (or empty if used as a string)

Comment on this Post


You must be logged-in to post a comment. Log-in/Register