Conditional Statements
Conditional Statements
If you want to process a different series of tests and act based on the results of these tests, there are a couple of ways you can go about this using Conditional statements . We have a choice of 2 statements in VBScript If..Then…Else and Select…Case .
If…Then…Else
You use this if you have one of two lines of code you need to execute . There are a variety of formats that this statement can take lets have a look at some of them .
If tme > 12 Then document.write(”hello good afternoon/evening”)
tme = hour(time) If tme > 12 Then document.write(”good evening”)This example is fine if you only wanted to test that the condition is true , i.e the hour is greater than 12 but if the hour is not greater than 12 nothing is displayed on the screen. So if you want to execute only one statement when a condition is true, this is the correct way to do it .
If tme < 12 then
document.write(”Good Morning”)
Else
document.write(”Good Afternoon / Evening”)
End If
If you want to execute some statements if a condition is true and execute others if a condition is false then the above syntax is what you would use , note this is better than the previous example because a message would be displayed on the screen all the time . The first block of code will be executed if the condition is true if tme < 12 then Good Morning is printed on the screen , the other block will be executed if the condition is false Good Afternoon / Evening.
You can also use ElseIf to make your code more readable like the following example
If (grade > 90 ) then
document.write(”Well done , a great score”)
ElseIf (grade > 75) then
document.write(”Good try”)
End If
in the above example we have only one ElseIf statement but we could have several . You can also nest If statements inside each other , like this .
If(grade1 > 90) then
If(grade2 > 85 ) then
statements would go here
If(grade2 > 75 ) then
statements would go here
End If
End If
Select Case
When a variable can take a number of different values then a Select Case statement can come in very handy . This has obvious advantages over the If statement in that it is far more readable .
Select case variable
case 1
statements to be executed 1
case 2
statements to be executed 2
case 3
statements to be executed 3
case else
default statement
End Select
First we have a single expression usually a variable, that is evaluated once. The value of the expression is then compared with the values for each case in the structure. If there is a match, the block of code associated with that case is executed . It is good programming practice to supply a default case else even if you know that this will never execute .
A case can also take multiple values and strings like the following examples
case 10 , 20 , 30
case “programmershelp”























