Consider the following bit of VBS:
dim msg, myVar, myVar2
msg = "myVar = " & myVar
msg = msg & vbcrlf & "myVar = empty: " & isempty(myVar)
msg = msg & vbcrlf & "TypeName(myVar) = " & TypeName(myVar)
msgbox msg, , "BEFORE"
if not myVar then myVar2 = true
msg = "myVar = " & myVar
msg = msg & vbcrlf & "myVar = empty: " & isempty(myVar)
msg = msg & vbcrlf & "TypeName(myVar) = " & TypeName(myVar)
msgbox msg, , "AFTER"
I would expect the output from "BEFORE" and "AFTER" to be the same... all we're doing is making a comparison to an uninitialised (empty) variant right?
However - it seems like the "if not" actually initialises it to a (long)zero! I've been coding in VBS (ASP) for donkey's years, and this is a new one on me!
A few things to note:
It seems like a potential trap for the unwary... Can anyone explain this behaviour?
In VBScript—where all variables are variants—variables can be one of two special values: EMPTY or NULL. EMPTY is defined as a variable with an un-initialized value, whereas NULL is a variable that contains no valid data.
Declaring Variables Variables are declared using “dim” keyword. Since there is only ONE fundamental data type, all the declared variables are variant by default. Hence, a user NEED NOT mention the type of data during declaration. Example 1 − In this Example, IntValue can be used as a String, Integer or even arrays.
The IsEmpty function returns a Boolean value that indicates whether a specified variable has been initialized or not. It returns true if the variable is uninitialized; otherwise, it returns False.
You can set the Boolean data type to either True or False, which are represented by -1 and 0, respectively, in VBScript. This subtype is useful when working with variables where you want to determine or set a condition.
I couldn't find anything official about this issue. After doing some test, I decided that this is a bug or an un-documented effect. This behaviour does not apply on other similar platforms like VBA and VB6.
Visual Basic for Application:
Visual Basic 6:
VBScript:
As a workaround, passing expressions by value works.
If Not (exp) Then
'or
If Not CBool(exp) Then
ByRef and ByVal Parameters
CBool Function
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With