CIS 209 Web Page Scripting Languages

Chapter 5: Programming with Control Structures

Decision control structures allow us to conditionally change the order in which a program is executed. Looping control structures allow us to repeat sections of code. Nested control structures make code easier to write and maintain.

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.

The assignment operator in both JavaScript and VBScript is the equal sign (=). JavaScript has additional assignment and arithmetic operators that are not supported in VBScript.

The concatenation operator is used to append expressions, such as a string and a variable. The concatenation operator in JavaScript is the plus sign (+), while the concatenation operator in VBScript is the ampersand (&).

Arithmetic Operators

Arithmetic operators allow you to perform mathematical calculations on values and variables. Because in JavaScript the arithmetic operator is the same key as the assignment operator, be careful that you do not append a string to a number. The number 1 and the string "1" are differentiated by the quotation marks. If you append a string to a number, for example 1 + a, the result will be the string "1a". The following table lists the arithmetic operators supported by both JavaScript and VBScript.

Operator     Description     Example     

+

Addition

x + y

-

Subtraction

x - y

*

Multiplication

x * y

/

Division

x / y

Notice how the parentheses change the order of operations in the following EXAMPLE.

Control Structures

There are two types of statements in VBScript and JavaScript:

  1. Action statements - code that carries out a task such as displaying text
    - steps are executed in the order in which they are written - known as linear programming
  2. Control statements - code that controls the execution order of scripts and action statements
    - allow you to conditionally determine whether and how an action statement is executed, and the order

Control structures use control statements to control the execution order of scripts and action statements. The benefits of using control structures include:

Programmers often indent action statements within a control structure to make it easier to identify control statements.

The two types of control structures are:

  1. Decision Control Structures
  2. Loop Structures

Decision control structures allow you to alter the execution order of action statements on the basis of conditional expressions. A conditional expression is an expression that is evaluated by the scripting engine as true or false. Loop structures allow you to repeat action statements on the basis of conditional expressions.

Both types of control structures use control statements to alter the order in which action statements are executed. There are three types of control statements:

  1. Looping statements - allow you to conditionally repeat a block of code
  2. Branching statements - program decides which block of code to run, based on criteria in the control statement
  3. Jumping statements - allow you to conditionally exit a code block and jump to another section of code

Both JavaScript and VBScript support looping statements, branding statements and jumping statements. These three types of control statements can be used in both client-side and server-side scripting.

Algorithms and flowcharts make visually clear the sequence in which a script is executed. It is a good idea to plan and write out the order in which you want the script to be able to execute, before writing the code.

Decision Control Structures

Decision control structures allow the program to select which statements to execute. The If Then statement, supported in both VBScript and JavaScript, allows only two options for altering the order in which statements are executed. The Select Case statement provides more than two options, but is only supported by VBScript. JavaScript uses a Switch Case statement to provide the same functionality.

If Then Statements

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 condition is true or false. In JavaScript, a pair of parentheses encloses the conditional expression.

If the condition is true, the code immediately following the conditional expression is executed. VBScript uses the keyword then to identify the code to execute if the condition is true. JavaScript uses curly braces to identify two blocks of code. When a condition is false, the program skips the first block of code and moves to the next block of code. The keyword else identifies where the next block of code begins. VBScript uses the keywords end if to identify the end of the conditional expression. JavaScript uses the closing curly brace to identify the end of the block of code.

The syntax for the If Then statement follows:

 VBScript

if CONDITION then
   code to run if TRUE
else
   code to run if FALSE
end if

 JavaScript

if (CONDITION) {
   code to run if TRUE;
}
else {
   code to run if FALSE;
}

In JavaScript, the semicolon is used as a terminator for action statements. There is no semicolon after the If or Else statements since these are control statements, not action statements.

Conditional Expressions: Conditional Expressions often consist of two expressions and a comparison operator. The expression can be a value, such as a number or a string, or a variable, or even another expression. The following table lists the comparison operators in JavaScript and VBScript.

Condition Being Tested    JavaScript   
Operator    
JavaScript Example    VBScript   
Operator
 
VBScript Example    
Equal to

==

var1 == var2

=

var1 = var2

Not equal

!=

var1 != var2

<>

var1 <> var2

Less than

<

var1 < var2

<

var1 < var2

Greater than

>

var1 > var2

>

var1 > var2

Less than or equal to

<=

var1 <= var2

<=

var1 <= var2

Greater than or equal to

>=

var1 >= var2

>=

var1 >= var2

The following EXAMPLE demonstrates the IF THEN statement in JavaScript. Notice that if the user checks the YES option, the program responds with a "Thank you", if not, it responds with "You may sign up later".

The radio button must be referred to by its index number since the name property for the radio button is the name for the group of buttons, not the individual button.

This EXAMPLE demonstrates the IF THEN statement in VBScript. The programming principles are the same, just the syntax is a bit different in VBScript.

Logical Operators: We can combine two conditional expressions and test them at the same time. A logical operator is used to compare two or more conditional expressions. The following table lists the logical operators used in JavaScript and VBScript. Although the operators are different, the meanings are the same.

JavaScript JavaScript Example VBScript   VBScript Example Meaning

&&

if(a==1)&&(b==2)

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.

|| (Pipe)

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. The NOT operator takes a single Boolean expression and reverses its value.

Each conditional expression must be enclosed in parentheses.

In our last example, we did not check to see if the user left the name text box empty. We can test that condition by combining multiple expressions using logical operators. Check out the following two examples.

JavaScript Example and VBScript Example

Nested If Then Statements: When one condition is met, the block of code that is executed may contain another If Then conditional statement, which becomes a nested If Then statement. The following examples accomplish the exact same result, but, they use a nested If Then statement to do it.

JavaScript Example and VBScript Example

Select Case Statements

The Select Case statement allows more than two conditions in the conditional expression. Although it is possible to nest many nested If Then statements to accomplish the same result, the Select Case statement will make your code much shorter and easier to follow. Because the Select Case statement is only supported by VBScript, it is most often used with server-side scripts.

An expression is evaluated using the keyword case . If the expression evaluates to true, then the code associated with the case statement is executed. If not, the next case expression is tested, and this continues through all the case statements until a condition is met. If no condition is met, we can add an optional case else statement to assign an action if no other condition is met. The Select Case statement ends with the keywords end select . The general syntax is:

select case VariableName
case Value1
   code to run if VariableName=Value1 (action statements)
case Value2
   code to run if VariableName=Value2 (action statements)
case Value3
   code to run if VariableName=Value3 (action statements)
case Value4
   code to run if VariableName=Value4 (action statements)
case else
   code to run if VariableName did not equal any of the values above
   (action statements)
end select

You can add as many case statements as you like. This example just lists 4 cases, plus the case else . Also, you can include any number of action statements under each case statement. You can call functions, set properties, calculate totals and write to the browser - anything you can otherwise do with scripts. Check out the Gift Finder example.

Switch Case Statements

JavaScript uses a Switch Case statement that is similar to the VBScript Select Case statement. JavaScript uses the keyword switch to identify the beginning of the statement. The entire statement is enclosed in curly braces, so there is no need for and ending statement. Each condition is identifies with the case keyword, and each case is stopped by the break keyword. The default keyword is used in place of the VBScript case else statement. Here is the syntax:

switch(VariableName){
case value1:
   code to run if VariableName=Value1;     (action statements)
   break;
case value2:
   code to run if VariableName=Value2;     (action statements)
   break;
case value3:
   code to run if VariableName=Value3;     (action statements)
   break;
case value4:
   code to run if VariableName=Value4;     (action statements)
   break;
default:
   code to run if VariableName did not equal any of the values above
   (action statements)
   break;

This EXAMPLE demonstrates how we can use the Switch Case statement instead of the VBScript Select Case statement to code the Gift Finder example above.

Loop Structures

The loop structure allow us to repeat a block of code any number of times. 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 the loop is called an iteration. The number of iterations can be explicitly stated or stored in a variable. A variable that keeps track of 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 forget to include the update statement, the program will continue until the browser is exited or the computer is turned off. When a loop continues without a natural ending it is called an infinite loop. The loop uses a conditional expression to determine when to stop. The loop stops when the condition is true.

The two main looping structures are:

  1. While Do Loops
  2. For Next Loops

The Do While Loop is an alternate version of the While Do Loop. The For In loop is a modified version of the For Next Loop. Although the structures vary in their syntax, all the loops allow you to repeat blocks of code.

While Do Loops

The While Do loop repeats a block of code for as long as a conditional expression is true. The conditional expression is identified by the keyword while . After each iteration is completed, the conditional expression is evaluated again. Here is the syntax for the While Do loop in JavaScript:

while (conditional expression){
   action statements;
   update statement;
}

In this EXAMPLE, an array stores the names of five departments.

In this example, the number of iterations was predetermined. We could have retrieved this number from the value from a form field as follows:

var numMax=document.frm.txtNumber.value;

Or, we could retrieve this number from a property, such as the length property of the array object as follows:

var numMax=document.write(Products.length);

Unary Operators: Unary operators are used to alter the value of a variable. The increment operator is ++ and increases the value by one. The decrement operator is -- and decreases the value by one. The negation operator is - and will change the sign to negative. Unary operators apply to both JavaScript and VBScript. Let's take another look at the line i++; in the example above.

Do While Loops

In a Do While loop, the conditional statement is evaluated first. If the condition is false, the loop does not process any code. The syntax for a Do While loop in JavaScript follows:

do{
   action statements;
   update statement;
}
while (conditional expression);

The following EXAMPLE illustrates how to implement the Do While loop using JavaScript.

The syntax is slightly different in VBScript. The conditional expression appears immediately after the keyword do, and the end of the loop is defined by the keyword loop . The parentheses around the conditional expression is not needed. The update statement just adds the number one to the index number. Check out the EXAMPLE of a Do While loop using VBScript.

For Next Loops

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 loop index number is declared before the loop begins.

In VBScript, the loop body begins with the keyword for . The update statement is identified by the keyword step . Step is an optional, and if omitted, equals one. The VBScript syntax for the For Next loop follows:

for LoopIndexVariable = START to STOP STEP StepValue
   action statements
next

This EXAMPLE demonstrate the use of the For Next loop in VBScript.

JavaScript is similar but, we'll use a semicolon to separate statements and we will omit the NEXT keyword since the end of the loop will be identified with a curly brace. The JavaScript syntax for the For Next loop follows:

for(START;CONDITON;INCREMENT) {
   action statements;
}

This EXAMPLE demonstrates the use of the For Next loop in JavaScript:

For In Loops

The For In loop is often used to retrieve the properties of objects and the collections of objects. The number of iterations is not based on a loop index number, but on the number of properties or elements within the object. Thus, the for statement must contain the name of the variable that will hold the name of the element, the keyword in, and the name of the object.

The syntax for implementing the For In loop using JavaScript follows:

for(variable in object){
   action statements;
}

Because the list of properties and objects constitutes an array for the document object, each element can be referred to by its index value in the array. The document([eachKey]) statement retrieves the value for that element in the document array. We can use document.title to refer to the name of the property. Properties and methods that are undefined will appear as "null".

This EXAMPLE uses the For In loop to list the properties of an object.

VBScript uses parentheses to retrieve the array element. Instead of using the keyword for , VBScript uses the keywords for each . The keywords exit for , which are optional, cause the program to exit the loop. The syntax for creating a For In loop in VBScript is:

for each(eachElement in object)
   action statements
   exit for
next eachElement

The index number for the array is named i in the following EXAMPLE. This allows us to retrieve the individual array elements by using the name of the array and the index number of the element.

TIP: Don't forget to check out THIS LINK (282GetFormValues.htm) on obtaining form values. It has working examples with the code and should help you to be able to write code with a control structure to deal with the form values the user enters.