CIS 179 – Web Script Programming     Lecture Notes

Tutorial 4 - Decision Making and Loops

A Numerical Accuracy Problem

Because of the way JavaScript stores real numbers, the equality operator ==, should not be used to compare two real numbers. Instead of doing a direct comparison you should compare the difference of the two numbers to some very small constant. (e.g.

x/y == 0.35

should be programmed as;

abs(x/y - 0.35) < EPSILON (where EPSILON = 0.0000001)

The if-else Statement

if (expression)
  statement1; //do this when expression is true
else
  statement2; //do this when expression is false

The else expression may be omitted.
if (expression)
  statement1; //do this when expression is true

if (taxable <= WAGE_LIMIT)
  taxes = RATE1 * taxable;
else
  taxes = RATE2 * (taxable - WAGE_LIMIT) + BRACKET1_TAX;


Compound Statements

A compound statement is any number of single statements contained between braces. Compound statements may be used with if-else statements.

Nested if Statements

The if-else Chain
if (exp1)
  statement1;
else if (exp2)
  statement2;
else
  statement3;
Exercise caution when arranging if-else chains. The first expression that is true determines which statements will be executed. The remainder of the statements in the chain will be skipped. If the expressions are not in the correct sequence, you can get an if-else chain where it is impossible to reach the interior statements.

The switch Statement

switch (expression)
{
  case value_1: // values can be different types
    sta_1;
    sta_2;
    .
    .
    break; // ends the switch statements
  case value_2:
    sta_m;
    sta_n;
    .
    .
    break; // forgetting break causes all remaining ...
    .      // statements to be executed
    .
  case value_m: case value_n: case value_o:
    sta_w;
    sta_x;
    .
    .
    break;
  default: // optional
    sta_aa;
    sta_bb;
}


Example:

var num;
for (num=1; num <= 5; num++) {
  switch (num) {
    case 1:
      document.writeln("num = 1");
      break;
    case 2: case 3:
      document.writeln("num = 2 or 3");
      break;
    default:
      document.writeln("num >= 4");
  }
}
Common Programming Errors
Using the assignment operator, =, in place of the relational operator ==. For example: if (opselect = 2)
  cout << "Happy Birthday";
else
  cout << "Good Day";
Always results in the message Happy Birthday being displayed.

HTML

Radio Buttons

A radio button is so named because it behaves like the buttons on a car radio. That is, only one of the buttons may be selected at any one time. Selecting a different button automatically deselects the current selection. Radio buttons are grouped together by giving them the same name.

<SCRIPT LANGUAGE="JavaScript1.2">
<!-- Hide from incompatible browsers
// function to handle radio button
function scoreQuest(answer) {
  switch (answer) {
    case "a":
      alert("Sorry Wrong Answer :(");
      break;
    case "b":
      alert("Sorry Wrong Answer :(");
      break;
    case "c":
      alert("Sorry Wrong Answer :(");
      break;
    case "d":
      alert("Of course, Captain Christopher Pike :)");
  }
}
// Stop hiding from incompatible browsers -->
</SCRIPT>

<!-- Display a question along with four possible answers using radio buttons -->
<FORM>
<B> Who was the very first captain of the starship Enterprise?</B><P>
<INPUT TYPE=radio NAME=quest1 VALUE="a"
    onClick="scoreQuest(this.value)">Captain Kirk<BR>
<INPUT TYPE=radio NAME=quest1 VALUE="b"
    onClick="scoreQuest(this.value)">Captain Picard<BR>
<INPUT TYPE=radio NAME=quest1 VALUE="c"
    onClick="scoreQuest(this.value)">Captain Janeway<BR>
<INPUT TYPE=radio NAME=quest1 VALUE="d"
    onClick="scoreQuest(this.value)">Captain Pike<BR>
</FORM>



Radio Button Example

Who was the very first captain of the starship Enterprise?

Captain Kirk
Captain Picard
Captain Janeway
Captain Pike



The while statement while (expression) // loop expression is true
statement;
 


 
 
 

Make sure the expression is modified inside the loop structure or the program will loop forever (an infinite loop).
 

// this is an infinite loop
while (count <= 10)
  document.writeln(count);

// an example that loops 10 times
var count = 1;
while (count <= 10) {
  document.writeln(count);
  count++; // increment count
}

// an example that counts backwards
var count = 10;
while (count > 0) {
  document.writeln(count);
  count--; // increment count
}

The do Statement
Like the While statement but evaluates the expression at the bottom of the loop. do
  statement;
while (expression);

var count = 2;
do {
  document.writeln("The count = " + count);
  count++;
} while (count < 10);

The statements inside the body of the do loop are always executed at least once. With the while loop the statements may not be executed at all.

The for Statement
The for statement is generally used in cases when you know in advance how many loop iterations you want to perform.

for (initializing list; expression; altering list)
  statement;
Each of the items is optional but the semicolons must be present. The statement is executed while the expression evaluates to true. The for statement can be thought of as a special case of the while loop. for (count = 2; count <= 20; count += 2)
  document.writeln(count);
It is generally a bad idea to modify the for loop index inside the body of the loop. If you need to do this a while loop would be a better choice.

The for…in Statement
A loop structure that automatically loops through all of the properties within a JavaScript object. The syntax is:

for (variable in object) {
  statement(s);
}
The for…in statement automatically assigns each property from object to the variable specified, performs the necessary statements on the property, then moves to the next property and starts over. The for…in statement ends when it reaches the last property in an object. A typical use is to display all of an object’s properties.
function Animal(type, sound, transport) {
  this.animal_type = type; // object property
  this.animal_sound = sound; // object property
  this.animal_transport = transport; //object property
}

livestock = new Animal("cow", "moo", "walk"); // instantiate object
for (prop in livestock) {
  document.writeln(prop); // print the names of the properties
}


The output of the above loop would be:

animal_type
animal_sound
animal_transport
 

with Statement
The with statement is used when working with object properties. Using the with statement saves you from continually retyping the name of the object when referencing multiple properties from the same object. The syntax for the with statement is:

with (object) {
  statement(s);
}


The following is an example that illustrates the usage of the with statement:

// accessing properties without the with statement
document.writeln("Mark Twain wrote: ");
document.writeln("Everybody talks about the weather, ");
document.writeln("but nobody does anything about it.");

// accessing properties using the with statement
with (document) { // no need to type document.
  writeln("Mark Twain wrote: ");
  writeln("Everybody talks about the weather, ");
  writeln("but nobody does anything about it.");
}

break and continue Statements
A break statement forces an immediate exit from the innermost enclosing switch, while, for, or do-while statement. // A demo of break
for(var count=1; count <=5; count++) {
  if(count == 3)
    break;
  document.writeln(count);
}

The previous loop results in the following display:

1
2

// A demo of continue
for(var count=1; count <=5; count++) {
  if(count == 3)
    continue;
  document.writeln(count);
}

The previous loop results in the following display:

1
2
4
5

Exercises

Page 198 numbers 2, 3 and 4