Ternary Operators in VBScript

January 17th, 2008

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.

Please use the trackback link when linking to this post.

Related Posts:

Add to Technorati Favorites

3 Responses to “Ternary Operators in VBScript”

  1. sandrar Says:

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

  2. Nilpo Says:

    Thanks, Sandra. I appreciate your kind words.

  3. what Says:

    This is NOT AT ALL the same thing as the ternary operator!!

    Your example was

    If blnCondition Then strResult = “true” Else strResult = “false”

    But the ternary operator would work like this:

    strResult = blnCondition ? “true” : “false”

    Note how strResult is only written once. There is a fundamental difference between the actual If block and the ternary operator… namely that If is a control structure and the ternary operator is, well, an operator.

    Let me guess, you’ve never taken a programming languages class….

Leave a Reply

.htaccess Apache article articles by Nilpo ASP ASP Free automation clipboard desktop Dev Shed docx drive Internet Explorer Microsoft PHP registry remove script scripting text tutorial tweak tweets Twitter UAC updates User Account Control VBS VBScript vista volume Windows Windows 7 Windows 2000 Windows Guru Windows Script Windows Script Host Windows Scripting Windows Vista Windows XP Word WScript wscript.exe WSH XP