<!-- SophiaKnows -->

JAVASCRIPT BASICS
Rev 4: December 2004

<  PART:   A · 1 · 2 · 3 · 4 · 5 · 6 · 7 · 8 · 9  >

 

3. What are JavaScript Control Structures?

JavaScript control structures both channel the flow a of a program's execution as well as automate execution of redundant tasks and operations.

The syntax for the five most common control structures are shown below: the for-in loop, for loop, while loop, the if loop and the if-else loop:


3.1 The JavaScript For-In Loop

The for-in loop is used to iterate through the keys and values in an associative array automating retrieval of member text-key/text-value elements:

for(text-keys in array-name) {
   [statements];
   }

array-name is name of the associative array the developer wants to iterate through. text-keys is a variable label designated by the developer to hold the list of text-keys found in the array.

The final listing in the last section (Part 3) showed an associative array of employee records with a somewhat cumbersome syntax and retrieval method.

Here is a for-in loop designed to run through the text-keys found in the array employees using a variable named keys to hold the value of the text-keys. Note that the statements in the loop will execute once for each instance of employee

for(keys in employees) {
   [statements];
   }

Note also that on each pass the value of keys will be the text-key for the current employee, or in this case a last name:

Listing 3.1 For-In Loop
var employees = new Array();

employees['Gould']={ f_name : "Glenn", l_name : "Gould", phone : "547" };
employees['Marx']={ f_name : "Allan", l_name : "Marx", phone : "542" };
employees['Peters']={ f_name : "Mary", l_name : "Peters", phone : "544" };
employees['Wilson']={ f_name : "Carl", l_name : "Wilson", phone : "548" };

for ( keys in employees ) {
    document.write("<p>"+ keys + ": x " +employees[keys]['phone']);
	}


3.2 The JavaScript For Loop

The basic for loop can be used to implement a mathematical progression through an ordered list of variable objects using the following basic syntax:

for(counter=value;[conditions];[operation]) {
   [statements];
   }

The [conditions] are conditions (typically a value comparison) that must be true in order for the progression to continue.

The [operation] most typically results in a simple incremental progression of the [counter]. (Note that the shorthand i++ is equivalent to saying: i=i+1):

for(i=0;i<somevalue;i++){ [statements]; }

Note that based on the [conditions] set in the example above, the loop will repeat so long as the [counter] (i) is less than (<) the value of somevalue

The value of somevalue can be a literal integer value (4, 100). Somevalue can also be a variable object or the results of an operation:

for(i=0;i<10;i++) { [statements];}
for(i=0;i<(n+10);i++) { [statements];}

Finally, and most conveniently, the value of somevalue can be the length (.length) of a variable object, most typically an Array() or other list object. In this instance, the value of the counter is used to sequentially retrieve list or array items by their corresponding list index using the following generic syntax:

for(i=0;i<array-label.length;i++) { document.write(array-label[i];}

To provide a more concrete example, we'll recycle the 4 item students and grades arrays demonstrated in the Arrays section. And this is what a for loop might look like cycling through and sequentially printing each item included in the two sample arrays:

Listing 3.2 For Loop
students=new Array("Tom","Mary","Anne","Ahmed");

var grades=new Array();
grades['Ahmed']="A+";
grades['Mary']="A";
grades['Tom']="B";
grades['Anne']="C";

for(i=0;i<students.length;i++) { 
   document.write("<br>"+students[i]+": "+grades[students[i]]);
   }
Tom:B
Mary:A
Anne:C
Ahmed:A+

The examples so far use the short hand increment operator (++) to increment the value of the counter by one on each pass. Conversely, the decrement operator (--) can be used to apply a similar shorthand (i--) to decrement a value by one (i=i-1) on each pass.

When reversing the progression the counter is initialized to the highest index in the list (length-1) and must now be greater than (>) somevalue (0) for the progression to continue:

for(i=students.length-1;i>0;i--) { [statements];}

Inverting the progression like this can be particularly useful when for example the programmer is retrieving items from a generally date ordered list and wants the most recent item (or last item in the list) to appear as the first item in the displayed results.


3.3 The JavaScript While Loop

Much like the for loop, the while loop continues to execute a set of bracketed statements while a set of [conditions] remain true:

while ([conditions])  { [statements];}

The conditions can be a value comparison or a primitive test for the existence of an object.

Unlike the for loop, however, values and operations affecting the truth of the conditions are defined outside the scope of the basic loop syntax (although they may fall, in part, within the bracketed statements).

Listing 3.3 While Loop
students=new Array("Tom","Mary","Anne","Ahmed");

var grades=new Array();
grades['Ahmed']="A+";
grades['Mary']="A";
grades['Tom']="B";
grades['Anne']="C";

var i = students.length-1;
while (students[i]) { 
   document.write("<br>"+students[i]+": "+grades[students[i]]);
   i--;
   }
Ahmed:A+
Anne:C
Mary:A
Tom:B

In this example an extrinsic counter i is assigned the value of the highest index in the students array (length-1) before the loop begins. Thereafter, so long as students[i] returns a defined value, the loop continues, a student name and grade is printed and i is decrement by 1 (i--);

When i==-1 the value students[-1] returns an undefined or false value. The conditions are no longer true, and the loop halts.


3.4 The JavaScript If Construct

The if construct conditionally executes a set of bracketed statements using the following generic syntax.

if([conditions]) {
   [statements];
   }

If the [conditions] within the parenthesis are true, the [statements] within the brackets (braces) will execute, otherwise not.

The most primitive true/false condition that can be tested is wether a true (non-zero, non-null) value has been assigned to a variable object.

The following example test for a true value in the variable demoMessage. Note that in this example the document.write() method will execute because the variable demoMessage has been declared in the code prior to the testing for the condition:

Listing 3.4 If Construct True
var demoMessage="I am here";
if(demoMessage) {
   document.write(demoMessage);
   }
I am here

Note that in the following example, however, the document.write() method will not execute because the variable demoMessage is initialized to a null string "":

Listing 3.5 If Construct False
var demoMessage="";
if(demoMessage) {
   document.write(demoMessage);
   }
 

As noted in the introduction, confirm() has a true/false result value. This can be tested as a condition using the following generic syntax:

Listing 3.6 If Construct Confirm
<a href=#
   onclick="if(confirm('alert now?')) {alert('you said yes');}">
   Do Alert?
</a>

When the user clicks the link a dialog cofirm displays the message 'alert now'. If the user selects [Cancel] the result is false and nothing happens. If the user selects [OK] the result is true and the alert between the braces sounds.

In addition to this primitive circumstance, the If Construct allows testing for more complex conditions (equality, inequality etc.) using the comparison operators discussed in the Comparison Operators section below. The related behaviors and extended syntax are demonstrated there.


3.5 The JavaScript If Else Construct

If the conditions within the parenthesis are true, the [statements] within the first set of braces will execute, otherwise the [alt-statements] in the braces following the reserved word "else" will execute:

if([conditions]) {
   [statements];
   } else {
      [alt-statements];
      }

The If Else loop extends the function of the basic If Construct by allowing the programmer to assign a default or alternative behavior to be executed when the conditions are not met.

As in the previous examples, the following tests for the existence of an object labeled demoMessage. This time however, if demoMessage has not yet been assigned (i.e. initialized), a default, string literal message will be printed instead:

Listing 3.7   If Else True
var username="Tom_G";

if(demoMessage) {
   document.write(username);
   } else {
       document.write("Anonymous");   
       }
Tom_G
Listing 3.8   If Else False
var username="";

if(demoMessage) {
   document.write(username);
   } else {
       document.write("Anonymous");   
       }
Anonymous

Finally, here is a primitive log on using the results of a prompt() dialog to gather a username.

Listing 3.9 If Else Prompt()
<a href="#"
  onclick="if(user=prompt('username')){alert(user);}else{alert('anonymous')}">
  log on?
</a>

If the user enters some text in the dialog and clicks [OK] the results of prompt() are true and an sounds printing the value input by the user. If the user enteres no text or clicks [Cancel] the results of prompt() are false and the alternate statements open an alert printing the default name 'anonymous'

As with the If Construct, the If Else Construct allows testing for more complex conditions (equality, inequality etc.) using the comparison operators discussed in the Comparison Operators section below. The related behaviors and extended syntax are demonstrated there.

 

Part 3 of 9 | Next Part 4: Comparison Operators >

<  PART:   A · 1 · 2 · 3 · 4 · 5 · 6 · 7 · 8 · 9  >

< CODEBASE | TOP^ | MAINPAGE >

Text & Design By Tony Pisarra
© SophiaKnows 1998-2004