VBScript If Statements

VBScript supports conditional statements like the If statement. Code will only run if a given condition is true.

VBScript If statements are a handy tool for any VBScript programmer. In fact, If statements are a universal to all programming languages (that I'm aware of).

An If Statement allows you to tell your program to do something only if a condition is true.

For example, you might have a website that asks the user what color their hair is. You could write code that only executes if their hair is say, black. OK, that's a pretty lame example but you get the idea!

Example If Statement

In this example, we'll stick with the lame subject of hair color, but to keep it simple, we won't ask for user input. We'll just set a variable with a hair color values.

This results in:

Same color as my cat!

If Else Statement

An If Else statement is an extension to the If statement. This allows you to tell the program to do something else in the event that the condition is not true.

This time the value of hairColor is blue. Because it is not black, the Else part of the statement is executed.

This results in:

Oh well, whatever...

Elseif Statement

You can add an Elseif to test for another condition if you like. You could do as many of these as you like too.

This time the Elseif code is executed because the value of the hairColor variable is blue.

This results in:

Same color as my parrot!