Search code examples
if-statementsyntaxvbscriptasp-classic

How to do a single line If statement in VBScript for Classic-ASP?


The "single line if statement" exists in C# and VB.NET as in many other programming and script languages in the following format

lunchLocation = (dayOfTheWeek == "Tuesday") ? "Fuddruckers" : "Food Court";

does anyone know if there is even in VBScript and what's the extact syntax?


Solution

  • The conditional ternary operator doesn't exist out of the box, but it's pretty easy to create your own version in VBScript:

    Function IIf(bClause, sTrue, sFalse)
        If CBool(bClause) Then
            IIf = sTrue
        Else 
            IIf = sFalse
        End If
    End Function
    

    You can then use this, as per your example:

    lunchLocation = IIf(dayOfTheWeek = "Tuesday", "Fuddruckers", "Food Court")
    

    The advantage of this over using a single line If/Then/Else is that it can be directly concatenated with other strings. Using If/Then/Else on a single line must be the only statement on that line.

    There is no error checking on this, and the function expects a well formed expression that can be evaluated to a boolean passed in as the clause. For a more complicated and comprehensive answer see below. Hopefully this simple response neatly demonstrates the logic behind the answer though.

    It's also worth noting that unlike a real ternary operator, both the sTrue and sFalse parameters will be evaluated regardless of the value of bClause. This is fine if you use it with strings as in the question, but be very careful if you pass in functions as the second and third parameters!