VBScript Conditional Statements
Conditional statement
Conditional statements are used to perform different actions based on different conditions.
In VBScript, we can use four conditional statements:
- If Statement - Use this statement if you want to execute a series of code when a condition is true
- If...Then...Else Statement - Use this statement if you want to execute one of two sets of code
- If...Then...ElseIf Statement - Use this statement if you want to select one of several sets of code to execute
- Select Case Statement - Use this statement if you want to select one of several sets of code to execute
If...Then...Else
Use the If...Then...Else statement when:
- executing a block of code when a condition is true
- selecting one of two blocks of code to execute
If you are executing onlyonestatement when a condition is true, you can write the code on a single line:
If i=10 Then alert("Hello")
In the code above, there is no ..Else.. statement. We only make the code execute when the condition is true (when i=10)one action。
If you are executing more thanonestatement when a condition is true, you must write one statement per line and use the keyword "End If" to end the statement:
If i=10 Then
alert("Hello")
i = i+1
End If
In the code above, there is also no ..Else.. statement. We only made the code execute when the condition is truemultiple actions。
If you want to execute one statement when a condition is true and another statement when it is not true, you must add the keyword "Else":
Example (for IE only)
Try it »
In the code above, the first block of code is executed when the condition is true, and the second block is executed when the condition is not true (when i is greater than 10).
If...Then...ElseIf
If you want to select one of several blocks of code to execute, you can use the If...Then...ElseIf statement:
Example (for IE only)
Try it »
Select Case
If you want to select one of several blocks of code to execute, you can use the "Select Case" statement:
Example (for IE only)
Try it »
How the above code works: First, we need a simple expression (often a variable), and this expression is evaluated once. Then, the value of the expression is compared with the values in each Case. If there is a match, the code corresponding to the matched Case is executed.