Ternary Operators in VBScript

I use the ? an : operators when writing PHP. Are there similar operators available in VBScript? – Bill S.

Let me first give a basic introduction for those readers who don’t know PHP and may not understand what we’re talking about here. PHP allows you to make quick decisions using the ? and : operators. These logical operators are known as Ternary Operators and allow you to take a shortcut approach to a simple conditional block. A ternary operation returns the result of an expression. Therefore, it is most commonly used for a variable assignment. In php, the syntax looks like this:

$variable = (condition) ? expression1 : expression2

In the above example, condition is an expression and must evaluate to either True or False. When condition evaluates to true, $variable is assigned the result of expression2. If condition evaluates to false, $variable is instead assigned the result of expression3. In code, both examples perform the same task.

// Example 1 shows how a typical IF/Else block assigns a value based upon another value
if ($result == "yes") {
	$message = "yes";
} else {
	$message = "no";
}
echo "You chose " . $message;
 
 
// Example 2 shoes the same operation using Ternary operators
$message = ($result == "yes") ? "yes" : "no";
echo "You chose " . $message;

In both examples above we are assuming that $result has a value of either “yes” or “no”. We then assign a value to $message based upon whether or not the expression $result == “yes” evaluates to True or False. A more likely example would be used to assign a default value to a variable when a previous value has not been set as in the following examples:

// Example 1 assigns a default value to $value if one is not provided by POST data
if (empty($_POST['action'])) {
	$action = 'default';
} else {
	$action = $_POST['action'];
}
 
 
// In Example 2 this is more appropriately done in a single line using Ternary operators
$action = (empty($_POST['action']) ? 'default' : $_POST['action'];

The above is a typical example of how a page action can be determined when a single PHP file performs multiple tasks. In any case, now that you understand what Ternary operators are exactly–and how they work–let’s get back to VBScript!

After reading all of that and learning how cool Ternary operators can be, I have a bit of bad news; VBScript does not have any Ternary operators. Don’t get upset and close this page just yet. I haven’t made you read all of this for nothing. VBScript does provide another functionality that can be used to achieve a similar effect.

Here I am talking about the shorthand syntax of the IF THEN…ELSE block. It looks something like this:

If condition Then expression1 Else expression2

As long as you are only performing single expression within each block, you can put your entire IF statement on a single line. So, just as in PHP, you can make simple variable assignments very quickly and efficiently.

' A typical If Then...Else block for assigning a variable
If blnCondition Then
	strResult = "true"
Else
	strResult = "false"
End If
 
 
' The same can be accomplished using shorthand syntax
If blnCondition Then strResult = "true" Else strResult = "false"

As you can see, we can achieve a very similar effect using the shorthand notation. Here we are assigning a string value to the variable strResult depending upon whether or not blnCondition evaluates to True or False. As in my PHP example, this is very useful for assigning default values to variables.

' Assign a default value to a variable based upon another's value
If intValue <> 0 Then strValue = "equals" & intValue Else strValue = "was undefined"
WScript.Echo "The value of intValue " & strValue

Another great use for this technique is to instantiate an object if it doesn’t already exist.

' Instantiate an object only if it doesn't already exist
If objFso Is Nothing Then CreateObject("Scripting.FileSystemObject")
Set objFile = objFso.CreateTextFile("temp.txt")

In this last example, we can easily avoid an error trying to use a reference to the FileSystemObject that may not already exist. Notice how, in this case, we don’t even need to use the Else portion of our statement.

So while VBScript may not have Ternary operators for us to use, this question did provide me an opportunity to share another little gem that you may find useful. And in some cases, it may just be able to provide you with the same functionality.

Tags

Like the read? Share it!

4 Comments

  • Hi! I was surfing and found your blog post… nice! I love your blog. 🙂 Cheers! Sandra. R.

  • Thanks, Sandra. I appreciate your kind words.

  • my 2 cents.

    as far as I’ve been able to tell, you have to kludge it up in vbScript.

    Along the lines of (tested for basic cases, but obviously not foolprofed):

    function ternary( boolVal, trueVal, falseVal )
    if ( boolVal ) then
    ternary = trueVal
    else
    ternary = falseVal
    end if
    end function

    strResult = ternary((theVal=”0″ or theVal=”-1″),”zero or neg 1″, “positive”)

  • Hi JeffH,

    Your code works fine, but it really defeats the purpose of a ternary operator (which is to avoid having drawn out structures). Not only that, but the implementation of your function makes readability extremely difficult as well.

Contact

Wanna say hello?
Drop us a line!

You'll find us here

1 Microsoft Way,
Redmond,
WA 98052, United States