Why VBScript Logical Operators Aren’t

By on July 15, 2004

If you’ve ever lost a monitor to VBScript (from frustrated punching, mine has dents), Eric Lippert provides some solace in that there’s at least a reason why it behaves that way.

In JScript you can do something like this:

if (blah != null && blah.frob == 123)

and it works just fine. But in VBScript

If (Not Blah Is Nothing) And (Blah.Frob = 123) Then

Then if Blah actually is Nothing, this still crashes and dies, whereas JScript does not. What the heck is going on here?

What’s going on is that VBScript is not logical. VBScript is bitwise. All the so-called logical operators work on numbers, not on Boolean values! Not, And, Or, XOr, Eqv and Imp all convert their arguments to four-byte integers, do the logical operation on each pair of bits in the integers, and return the result. If True is -1 and False is 0 then everything works out, because -1 has all its bits turned on and 0 has all its bits turned off. But if other numbers get in there, all bets are off.

I didn’t say it was a good reason. I just said it was a reason.