CONTROL STRUCTURES CHAPTER OBJECTIVES Create scripts that use arithmetic, comparison, and logical operators Create conditional expressions Use If Then, Select Case, and Switch Case decision control structures to alter the execution order of a script Use Do While, While Do, and For Next looping control structures to repeat blocks of code Create nested blocks of code Operators Both VBScript and JavaScript support assignment, concatenation, arithmetic, comparison, and unary operators. Assignment operators are used to assign a value or an object to a variable. JavaScript and VBScript use the equal sign, “=”, as their assignment operator. JavaScript: VBScript: variable = value; variable = value The concatenation operator is used to append expressions, such as a string and a variable. JavaScript uses the plus, “+”, while VBScript uses the ampersand “&”. Examples: document.write (“The price of “ + totNumber + “apples is “ + totPrice ); document.write (“The price of “ & totNumber & “apples is “ & totPrice ) Arithmetic operators allow you to perform mathematical calculations on values and variables. VBScript + * / Control Strucutres JavaScript + * / Description Addition Subtraction Multiplication Division 1 Example x+y x-y x*y x/y Dr. M. Abdur Rob Control Structures There are two types of programming statements in VBScript and JavaScript: action statements and control statements. Action statements – consist of code that carries out a task, such as displaying text or assigning a value to a variable. These statements are usually executed in the order they are written (termed as linear programming). Control statements – allow you to conditionally determine both whether and how an action statement is executed, and the order in which action statements are executed. There are three types of control statements that are supported by both VBScript and JavaScript and can be used in both client-side and serverside scripting. Looping statements – allow you to conditionally repeat a block of code. Branching statements – allow the program to decide which of two or more blocks of code to run, basing its decision on some identified criteria in the control statement. Jumping statements – allow you to conditionally exit a code block and jump to another section of code within your program. Control Strucutres 2 Dr. M. Abdur Rob Decision control structures The If Then statement is the most frequently used decision control structure. The If Then statement allows a script to alter the order in which statements are executed, on the basis of a conditional expression. The conditional expression tests whether a certain condition is true or false The Select Case statement provides more than two options and is supported only in VBScript. JavaScript uses a Switch Case statement to provide the same functionality. The syntax for the If Then statement in VBScript is: If (conditional expression) then action statements else action statements end if The syntax for the If Then statement in JavaScript is: If (conditional expression) then { action statements } else { action statements } JavaScript uses brackets ({) to start and end the control structure, VBScript uses the ‘end if’ to declare that the control structure has ended. Conditional expressions often consist of two expressions and a comparison operator. The following table lists comparison operators used in conditional expressions in both JavaScript and VBScript. Condition Being tested Equal to Not equal Less than Greater than Less than or equal to Greater than or equal to Control Strucutres JavaScript Operator = = (no space) != < > <= >= JavaScript Example var1 == var2 var1 != var2 var1 < var2 var1 > var2 var1 <= var2 var1 >= var2 3 VBScript Operator = <> < > <= >= VBScript Example var1 = var2 var1 <> var2 var1 < var2 var1 > var2 var1 <= var2 var1 >= var2 Dr. M. Abdur Rob Example: emaillist.htm <html><head> <title>If Then Statements</title> </head> <body> <h1 align=”center”>Expression Test</h1> <form method="post" name="frm1" action="javascript:void(0)"> <input type ="text" value="??" name="txtName" size="8"> Name<br><br> Which color do you prefer? <p><input type="radio" checked name="Color">Red</p> <p><input type ="radio" name="Color">Blue</p> <input type="submit" value="Choose" name="btnChoose" onClick="colorpick()";></p> </form> <script> function colorpick(){ var strName = window.document.frm1.txtName.value; if(document.frm1.Color[0].checked==true){ window.alert(strName + " is a red person"); } else{ window.alert(strName + " is a blue person"); } } </script> </body></html> View: emaillistJS.htm emaillistVB.htm Syntax of script <form method="post" name="frm1" action="javascript:void(0)"> Explanation In JavaScript void is a special operator that does nothing. Void will cause nothing to occur, which prevents an error to occur in code that is expecting an action to occur. <input type="submit" value="Choose" name="btnChoose" onClick="colorpick()";></p> The button triggers a script function called colorpick(). The colorpick() function will access the variables set up in the form. if(document.frm1.Color[0].checked==true){ The conditional expression compares the first radio button, Color[0], with a true string. If it is true, the statements between the brackets {} will be executed. window.alert(strName + " is a red person"); This is the script statement that will be executed if the conditional statement evaluates to true. else{ If the statement does not evaluate to true these statements will be executed. The else statement is optional. window.alert(strName + " is a blue person"); Control Strucutres 4 Dr. M. Abdur Rob The example below illustrates how to process the same form using VBScript. Note only the colorpick() function is shown here. <script language=”vbscript”> function colorpick() dim strName = window.document.frm1.txtName.value if(document.frm1.Color(0).checked=true) then window.alert(strName + " is a red person") else window.alert(strName + " is a blue person") end if end function </script> Logical Operators A logical operator is used to compare two or more conditional expressions at the same time. They are different for JavaScript and VBScript. Java Script && Example Example Meaning if((a==1)&&(b==2)) VB Script AND if((a=1) and (b= 2 )) If both expressions are true, the result is true. If either expression is false, the result is false. || if((a==1)||(b==2)) OR if((a=1) or (b= 2 )) If either expression is true, or both are true, the result is true. If both are false, the result is false. ! if (!(a == 1)) NOT if(not(a = 1)) Used to negate a single expression. If the expression is true, the result is false. If the expression is false, the result is true. It is clear that VBScriot is simpler than the JavaScript, and all previous examples that is also true. Control Strucutres 5 Dr. M. Abdur Rob Nested If Then Statements You can nest one If Then statement within another If Then statement. The process of nesting can be done indefinitely. The following example shows a nested If Then example. Example in VBScript: IF grade > 89 THEN document.write (“Excellent!”) ELSE IF grade > 79 THEN document.write (“Above Average!”) ELSE IF grade > 69 THEN document.write (“Average!”) END IF END IF END IF Example in VJavaScript: if (grade > 89) then { document.write (“excellent!”) } else { if (grade > 79) then { document.write (“above average!”) } else if (grade > 69) then { document.write (“average!”) { } Control Strucutres 6 Dr. M. Abdur Rob Select Case Statements The Select Case statement, an extension of the If Then statement, is used to include more than two conditions in the conditional expression. The statement could be broken into many nested If Then statements, but if you use a Select Case statement, your code will be shorter, and also easier to follow. This statement is used mostly with server-side script since it is only supported by VBScript. Example: caseselectVB.htm: <html><head> <title>Case Select Statement</title> </head> <body bgcolor="#B1B6DE" text="#000080"> <h1>Case Select in VBScript</h1> <script language="vbscript"> dim strP strP = 1 select case strP case 1 window.alert ("The cost is $" & strP) case 2 window.alert ("The cost is $" & strP) case else window.alert ("The cost is $" & strP) end select </script> </body> </html> View caseselectVB.htm The statement checks to see if strP is equal to 1, and when that condition is true the statements related to that case are executed. If strP was initialized to 8, the case else would be executed. Example of nested IF THEN and Select Case: View giftfinderVB.htm code Control Strucutres View giftfinderVB.htm Web page 7 Dr. M. Abdur Rob Switch Case Statements JavaScript contains a Switch Case statement that is similar to the VBScript Select Case statement. Both allow you to evaluate multiple statements. JavaScript uses the keyword switch to identify the beginning of the statement. The entire statement is enclosed within curly braces ({}). <script language=”javascript”> function giveNumber(){ var strP; strP = document.frm.Number.value; switch (strP){ case 1: window.alert (“You picked number 1”); break; case 2 : window.alert(“You picked number 2”); break; case 3: window.alert(“You picked number 3”); break; default: window.alert(“You picked a number that wasn’t 1, 2 or 3”); break; } } </script> The switch could be replaced with the following If Then statements: If(strP==1){ window.alert (“You picked number 1”); } else if (strP==2){ window.alert (“You picked number 2”); { else if(strP==3){ window.alert (“You picked number 3”); } else{ window.alert(“You picked a number that wasn’t 1, 2 or 3”); } Control Strucutres 8 Dr. M. Abdur Rob Loop Structures Using a loop structure, you can repeat action statements or control statements any number of times. To list 100 elements in an array would take 100 statements without a loop structure and approximately 7 statements with a loop structure. The statements contained in the loop are called the body of the loop, and may consist of a single statement or several statements. Each repetition of a loop is called iteration. The number of iterations is referred to as a loop index variable. An update statement is used to determine how to change the loop index variable. If you never update the loop index variable the loop will continue to run without a natural ending, this is called an infinite loop. The loop uses a conditional expression to determine when to stop—the loop stops when the conditional expression is true. There are two main looping structures: While Do loops – the Do While loop is an alternative The For Next loops – the For In loop is an alternative The While Do loop will repeat a block of code for as long as a conditional expression is evaluated as true. The following is the syntax for a While Do loop in JavaScript. while(conditional expression) { action statements; update statement; } Control Strucutres 9 Dr. M. Abdur Rob The following example uses the While Do loop syntax above to display the elements of an array. <html><head> <title>While Do</title> </head> <body> <script language="javascript"> document.write("<h1>Departments</h1>"); var strLists = new Array(); strLists [0] = "Sports"; strLists [1] = "Toys"; strLists [2] = "Music"; strLists [3] = "Books"; strLists [4] = "Food"; var numMax = strLists.length; var i = 0; //New array and filling the array //using length property of the array while(i != numMax){ document.write((strLists[i]) + "<br>"); i++; } document.write("<br>There are " + i + " departments"); </script> </body></html> Syntax of Code var strLists = new Array(); Explanation This initializes the array. var numMax = strLists.length; This sets a variable to the length of the array, this variable will act as the final value for the update statement. var i= 0; The variable is i initialized to zero and this will be incremented each time the loop is executed. The variable i will represent the loop index variable. while(i != numMax){ This is the conditional expression that will be evaluated every iteration of the loop. document.write((strLists[i]) + “<br>"); This uses the index variable to print all the elements of the array. i++; This increments the loop index variable. Some type of increment has to be made or the loop will run forever. The ++ is a unary operator. Control Strucutres 10 Dr. M. Abdur Rob Unary Operators Unary operators are used to alter a value of a variable. In JavaScript: Operator ++ Purpose Increments a counter by 1 Example Count = ++ Count Result if Count = 5 Count = 6 -- Decrements a counter by 1 Count = -- Count Count = 4 - Negation: changes the sign to the inverse sign -Count Count = -5 Do While Loops The Do While loop structure is similar to the While Do structure. The only difference is the conditional evaluation is done at the end of the loop, which means there will be at least one iteration. Below is the syntax for a Do While loop in JavaScript. do { action statements; update statement; } while (conditional expression); Example in VBScript: dowhileVB.htm <html><head> <title>Do While</title> </head> <body> <script language="vbscript"> dim aNumber aNumber = 5 dim i i=0 do while i <= aNumber window.alert(i) i=i+5 loop </script> </body></html> Control Strucutres 11 Dr. M. Abdur Rob For Next Loops The For Next loop, like the Do While loop, repeats action statements for a fixed number of times. However the syntax is very different. The For Next loop identifies not only the conditional expression but also the loop index number and the update statement as parameters in the “for” statement. The following is the syntax for the VBScript For Next loop. For LoopIndex = startExpression to endNumber step stepNumber Action statements Next The following is an example of utilizing the VBScript For Next loop. <script language =”vbscript”> dim startNum, endNum, stepNum, I startNum = 0 endNum = 5 stepNum = 2 for i = startNum to endNum step stepNum window.alert(i) next </script> JavaScript also supports the For Next loop, and its syntax is as floows. Notice that the semicolons separate each statement from the next. for ( startExpression; conditional expression; stepNumber) { action statements; } The following is an example of utilizing the JavaScript For Next loop. <script language=”javascript”> for (var i =0; I<=5; I=I+1){ document.write(“Your number is “ + I + “<br>”); } </script> Control Strucutres 12 Dr. M. Abdur Rob For In Loops The For In loop is similar to the For Next loop in that they both allow you to repeat action statements. However, the For In loop is most often used to retrieve the properties of objects. The For In loop retrieves information about the properties of an object and the collections of the object. Below is the syntax for implementing the For In Loop using JavaScript. for(variable in object) { action statements; } The following is an example of For In loop in VBScript. ForInVB.htm <html><head><title>For In</title></head> <body bgColor="#FFFF99" > <h1>Elements of the Product Array</h1> <script language = "VBscript"> ‘New array and populating the array dim Products(5) Products(0) = "Pencils" Products(1) = "Pens" Products(2) = "Paper" Products(3) = "Markers" Products(4) = "Notepads" Products(5) = "Scissors" dim i i=0 ‘For Loop to print the array items for each eachElement in Products document.write(Products(i) & "<br>") i = i+1 next </script> </body></html> View ForInVB.htm Control Strucutres 13 Dr. M. Abdur Rob Sample Project: Project 5-1 ProductOrderVB.htm <html> <head><title>Product Order Form</title></head> <body bgcolor="#FFCC99"> <h1 align="center"><font color="#800000">Calculate Your Order</font></h1> <form method="post" name=frmProd action="javascript:void(0)"> <center> <div align="left"> <table border="0" width="83%" height="301"> <tr> <td width="64%" height="273" align="right" rowspan="7"> <h2 align="center"><font color="#800000">100 Black Pens!</font></h2> <h2 align="center"><img border="0" src="blackpens.gif" width="256" height="192"></h2> </td> <td width="60%" height="37" align="right"><font color="#800000" face="Trebuchet MS">Price:</font></td> <td width="7%" height="37"></td> <td width="46%" height="37"> <font color="#800000"> <input type="text" name="price" size="6" value="28.00"> </font> </td> </tr> <tr> <td width="60%" height="43" align="right"><font color="#800000" face="Trebuchet MS">Quantity:&nbsp;</font></td> <td width="7%" height="43"></td> <td width="46%" height="43"> <font color="#800000"> <select name="quantity" size="1"> <option selected value="1">1</option> <option value="2">2</option> <option value="3">3</option> </select> </font> </td> </tr> <tr> <td width="60%" height="43" align="right"><font color="#800000" face="Trebuchet MS">State:</font></td> <td width="7%" height="43"></td> <td width="46%" height="43"> <font color="#800000"> <select name="state" size="1"> <option value="0.085" selected>Illinois</option> <option value="0.07">Indiana</option> <option value="0">Other</option> Control Strucutres 14 Dr. M. Abdur Rob </select> </font> </td> </tr> <tr> <td width="60%" height="35" align="right"><font color="#800000" face="Trebuchet MS">Delivery Method:</font></td> <td width="7%" height="35"></td> <td width="46%" height="35"> <font color="#800000"> <select name="shipping" size="1"> <option selected value="0.02">Standard UPS</option> <option value="0.05">Overnight</option> <option value="0">Pickup</option> </select> </font> </td> </tr> <tr> <td width="111%" colspan="3" height="44"> <p align="center"><font color="#800000" face="Trebuchet MS">Your Total is:</font></td> <td><input type="text" name="total" size="11" value="0.00"></td> </tr> <tr> <td width="111%" colspan="3" height="44"> <p align="center"> <font color="#800000"> </font> </td> </tr> <tr> <td width="111%" colspan="3" height="27"> <p align="center"> <input name="btnSubmit" type="button" value="Calculate My Order Now!" onClick= "calcProd()"> </td> </tr> </table> </div> </center> </form> <script language="vbscript"> function calcProd() dim strPrice, strQuantity, strState, strTotal strPrice=document.frmProd.price.value strQuantity=document.frmProd.quantity.value strState=document.frmProd.state.value strShipping=document.frmProd.shipping.value strTotal=((strPrice*strQuantity)+(strPrice*strQuantity)*strState + (strPrice*strQuantity)*strShipping) document.frmProd.total.value= strTotal end function </script> </body> </html> View ProductOrderVB.htm Control Strucutres 15 Dr. M. Abdur Rob KEY TERMS Action statements – consist of code that carries out a task, such as displaying text or assigning a value to a variable. Arithmetic operators - allow you to perform mathematical calculations on values and variables. Boolean expression - a conditional expression; an expression that evaluates to true or false. Branching statements – allow the program to decide which of two or more blocks of code to run, basing its decision on some identified criteria in the control statement. Comparison operator – is used to compare two or more expressions. Conditional expression – is an expression that is evaluated by the scripting engine as true or false. Control statements – allow you to conditionally determine both whether and how an action statement is executed, and the order in which action statements are executed. Decision control structures - allow you to alter the execution order of action statements on the basis of conditional expressions. If Then statement - the most frequently used decision control structure. Infinite loop – when a loop continues without a natural ending. Jumping statements – allow you to conditionally exit a code block and jump to another section of code within your program. Logical operator – is used to compare two or more conditional expressions. Loop index variable – a variable that keeps track of the number of iterations. Loop structures - allow you to repeat action statements on the basis of conditional expressions. Looping statements – allow you to conditionally repeat a block of code. Unary operator – used to alter a value of a variable. Quick Quiz: 1. What is the name of the expression statement that is evaluated by the scripting engine as true or false? 2. Which statement is the most frequently used decision control structure. 3. Which decision control statement provides more than two options and is supported only in VBScript? 4. Can any select or switch statement be substituted for by nested If Then statements? 5. If you never update the loop index variable, the loop will continue to run without a natural ending. What is this called? 6. What is the least amount of times a While Do loop executes? 7. What is the least amount of times a Do While loop executes? 8. Which loop is used to obtain properties of an object? Control Strucutres 16 Dr. M. Abdur Rob