Tuesday 19 March 2013

ASP: conditional statements with If...Then...Else...ElseIf

   


In ASP we can use conditional statements in different ways. The basic syntax we are used to, is If ... Then ... Else ... End, however we will see that there are some interesting things about it.

First of all let's consider a simple conditional statement in ASP. As you already know, we do not use any brackets or parenthesis. A basic example could be:
<%
Dim numVar
numVar = 5
If numVar = 5 then
  response.write("The variable numVar is 5")
End if
%>

The above is just checking if numVar is equal to 5. If so, the text is output ("The variable numVar is 5"). Otherwise, nothing happens. It's obvious that the example will always output something, because 5 is always equal to 5.
Moreover, we must remember that in ASP we cannot set a value of a variable inside the conditional statement. The use of the operators (like "=") inside a conditional statement is always used only to compare two values, variables and values or variables and variables.

If we need to create a more complex conditional statement, we can introduce "Else". That means we can check if a condition is met, but if it's not we can decide what to do. What stays after the "Else" is what's happening if the first condition is false.
<%
Dim numVar
numVar = 5
If numVar = 6 then
  response.write("The variable numVar is 6")
Else
  response.write("The variable numVar is " & numVar)
End if
%>
The first condition is clearly false and the first response.write will be ignored, while the second will be executed.

We can create nested conditional statements, but believe me, in many situations, they can create strong headaches. We normally prefer to use a conditional statement at the time, however there's something more.

We can check multiple conditions using "ElseIf" which is a new conditional statement, depending on the first conditional statement.
Let's try to simplify it by using simple words:
If something is true Then do this ElseIf second something is true Then do this etc. Obviously we cannot use an "ElseIf" not "contained" in an If statement.
Let's see an example:
<%
Dim numVar
numVar = 5
If numVar = 6 Then
  response.write("The variable numVar is 6")
ElseIf numVar = 5
  response.write("The variable numVar is 5")
Else
  response.write("The variable numVar is " & numVar)
End if
%>
As you may notice, the above code will always output "The variable numvVr is 5".

I think that a good use of ElseIf can be very beneficial to our code, especially when we need to check different variables for multiple values.
If you have used it in special and interesting ways, please share your thoughts in the comments section below.

0 thoughts:

Post a Comment

Comments are moderated. I apologize if I don't publish comments immediately.

However, I do answer to all the comments.