Anticipating Full Evaluation of Logical Expressions

The VBScript programming language does not short-circuit evaluation of Boolean conditions. VBScript evaluates all the terms in a Boolean logical expression, even if the expression can be established as True or False without evaluating all its terms. For example, in the following example, both <statement1> and <statement2> are evaluated, even if <statement1> resolves to False:

<statement 1> AND <statement 2>

Recommendations

To avoid errors, check that all values and objects are not Null before attempting to use them.

The following examples:

  • demonstrate incorrect and correct usage of logical expressions
  • take into consideration how logical expressions are evaluated

Example: Incorrect Usage

value.Name is evaluated even when its value is Null. This causes an error.

Sub namecheck(value) 
        If Not IsNull(value) And value.Name = "aName" Then 
            ' ... 
          End If 
End Sub

Example: Correct Usage

The code is correct on the condition that value is an object that contains the Name property. The code runs without errors.

Sub namecheck(value) 
    If Not IsNull(value) And Not IsEmpty(value) Then 
         If value.Name = "aName" Then 
            ' ... 
        End If 
      End If 
End Sub