[Contents] [Previous] [Next] [Index]

Chapter 12
Overview of JavaScript Statements

JavaScript supports a compact set of statements that you can use to incorporate a great deal of interactivity in Web pages. This chapter provides an overview of these statements.

The statements fall into the following categories:

The following sections provide a brief overview of each statement. See the JavaScript Reference for details.

Conditional Statement

A conditional statement is a set of commands that executes if a specified condition is true. JavaScript supports two conditional statements: if...else and switch.

if...else Statement

Use the if statement to perform certain statements if a logical condition is true; use the optional else clause to perform other statements if the condition is false. An if statement looks as follows:

if (condition) {
   statements1
}
[else {
   statements2
} ]
The condition can be any JavaScript expression that evaluates to true or false. The statements to be executed can be any JavaScript statements, including further nested if statements. If you want to use more than one statement after an if or else statement, you must enclose the statements in curly braces, {}.

Example. In the following example, the function checkData returns true if the number of characters in a Text object is three; otherwise, it displays an alert and returns false.

function checkData () {
   if (document.form1.threeChar.value.length == 3) {
      return true
   } else {
      alert("Enter exactly three characters. " +       
      document.form1.threeChar.value + " is not valid.")
      return false
   }
}

switch Statement

A switch statement allows a program to evaluate an expression and attempt to match the expression's value to a case label. If a match is found, the program executes the associated statement. A switch statement looks as follows:

switch (expression){
   case label :
      statement;
      break;
   case label :
      statement;
      break;
   ...
   default : statement;
}
The program first looks for a label matching the value of expression and then executes the associated statement. If no matching label is found, the program looks for the optional default statement, and if found, executes the associated statement. If no default statement is found, the program continues execution at the statement following the end of switch.

The optional break statement associated with each case label ensures that the program breaks out of switch once the matched statement is executed and continues execution at the statement following switch. If break is omitted, the program continues execution at the next statement in the switch statement.

Example. In the following example, if expr evaluates to "Bananas", the program matches the value with case "Bananas" and executes the associated statement. When break is encountered, the program terminates switch and executes the statement following switch. If break were omitted, the statement for case "Cherries" would also be executed.

switch (expr) {
   case "Oranges" :
      document.write("Oranges are $0.59 a pound.<BR>");
      break;
   case "Apples" :
      document.write("Apples are $0.32 a pound.<BR>");
      break;
   case "Bananas" :
      document.write("Bananas are $0.48 a pound.<BR>");
      break;
   case "Cherries" :
      document.write("Cherries are $3.00 a pound.<BR>");
      break;
   default :
      document.write("Sorry, we are out of " + i + ".<BR>");
}
document.write("Is there anything else you'd like?<BR>");

Loop Statements

A loop is a set of commands that executes repeatedly until a specified condition is met. JavaScript supports two loop statements: for and while. In addition, you can use the break and continue statements within loop statements.

Another statement, for...in, executes statements repeatedly but is used for object manipulation. See "Object Manipulation Statements and Operators".

for Statement

A for loop repeats until a specified condition evaluates to false. The JavaScript for loop is similar to the Java and C for loop. A for statement looks as follows:

for ([initial-expression]; [condition]; [increment-expression]) {
   statements
}
When a for loop executes, the following occurs:

  1. The initializing expression initial-expression, if any, is executed. This expression usually initializes one or more loop counters, but the syntax allows an expression of any degree of complexity.

  2. The condition expression is evaluated. If the value of condition is true, the loop statements execute. If the value of condition is false, the for loop terminates.

  3. The update expression increment-expression executes.

  4. The statements execute, and control returns to step 2.
Example. The following function contains a for statement that counts the number of selected options in a scrolling list (a Select object that allows multiple selections). The for statement declares the variable i and initializes it to zero. It checks that i is less than the number of options in the Select object, performs the succeeding if statement, and increments i by one after each pass through the loop.

<SCRIPT>
function howMany(selectObject) {
   var numberSelected=0
   for (var i=0; i < selectObject.options.length; i++) {
      if (selectObject.options[i].selected==true)
         numberSelected++
   }
   return numberSelected
}
</SCRIPT>
<FORM NAME="selectForm">
<P><B>Choose some music types, then click the button below:</B>
<BR><SELECT NAME="musicTypes" MULTIPLE>
<OPTION SELECTED> R&B
<OPTION> Jazz
<OPTION> Blues
<OPTION> New Age
<OPTION> Classical
<OPTION> Opera
</SELECT>
<P><INPUT TYPE="button" VALUE="How many are selected?"
onClick="alert ('Number of options selected: ' + howMany(document.selectForm.musicTypes))">
</FORM>

do...while Statement

The do...while statement repeats until a specified condition evaluates to false. A do...while statement looks as follows:

do {
   statement
} while (condition)
statement executes once before the condition is checked. If condition returns true, the statement executes again. At the end of every execution, the condition is checked. When the condition returns false, execution stops and control passes to the statement following do...while.

Example. In the following example, the do loop iterates at least once and reiterates until i is no longer less than 5.

do {
   i+=1;
   document.write(i);
} while (i<5);

while Statement

A while statement executes its statements as long as a specified condition evaluates to true. A while statement looks as follows:

while (condition) {
   statements
}
If the condition becomes false, the statements within the loop stop executing and control passes to the statement following the loop.

The condition test occurs before the statements in the loop are executed. If the condition returns true, the statements are executed and the condition is tested again. If the condition returns false, execution stops and control is passed to the statement following while.

Example 1. The following while loop iterates as long as n is less than three:

n = 0
x = 0
while( n < 3 ) {
   n ++
   x += n
}
With each iteration, the loop increments n and adds that value to x. Therefore, x and n take on the following values:

After completing the third pass, the condition n < 3 is no longer true, so the loop terminates.

Example 2: infinite loop. Make sure the condition in a loop eventually becomes false; otherwise, the loop will never terminate. The statements in the following while loop execute forever because the condition never becomes false:

while (true) {
   alert("Hello, world") }

labeled Statement

A labeled statement provides an identifier that can be used with break or continue to indicate where the program should continue execution. A labeled statement looks as follows:

label : 
   statement
In a labeled statement, break or continue must be followed with a label, and the label must be the identifier of the labeled statement containing break or continue. The statements in a labeled statement can be of any type.

Example. A statement labeled checkiandj contains a statement labeled checkj. If break is encountered, the program breaks out of the checkj statement and continues with the remainder of the checkiandj statement. If break had a label of checkiandj, the program would break out of the checkiandj statement and continue at the statement following checkiandj.

checkiandj : 
   if (4==i) {
      document.write("You've entered " + i + ".<BR>");
      checkj :
         if (2==j) {
            document.write("You've entered " + j + ".<BR>");
            break checkj;
            document.write("The sum is " + (i+j) + ".<BR>");
         }
      document.write(i + "-" + j + "=" + (i-j) + ".<BR>");
   }

break Statement

The break statement can be used in a while, for, and labeled statement.

In a while or for statement, break looks as follows:

break
In a labeled statement, break looks as follows:

break label
Example 1. The following function has a break statement that terminates the while loop when i is three, and then returns the value 3 * x.

function testBreak(x) {
   var i = 0
   while (i < 6) {
      if (i == 3)
         break
      i++
   }
   return i*x
}
Example 2. A statement labeled checkiandj contains a statement labeled checkj. If break is encountered, the program terminates the checkj statement and continues with the remainder of the checkiandj statement. If break had a label of checkiandj, the program would terminate the checkiandj statement and continue at the statement following checkiandj.

checkiandj : 
   if (4==i) {
      document.write("You've entered " + i + ".<BR>");
      checkj :
         if (2==j) {
            document.write("You've entered " + j + ".<BR>");
            break checkj;
            document.write("The sum is " + (i+j) + ".<BR>");
         }
      document.write(i + "-" + j + "=" + (i-j) + ".<BR>");
   }

continue Statement

The continue statement can be used in a while, for, and labeled statement.

In a while or for statement, continue looks as follows:

continue
In a labeled statement, continue looks as follows:

continue label
Example 1. The following example shows a while loop with a continue statement that executes when the value of i is three. Thus, n takes on the values one, three, seven, and twelve.

i = 0
n = 0
while (i < 5) {
   i++
   if (i == 3)
      continue
   n += i
}
Example 2. A statement labeled checkiandj contains a statement labeled checkj. If continue is encountered, the program terminates the current iteration of checkj and begins the next iteration. Each time continue is encountered, checkj reiterates until its condition returns false. When false is returned, the remainder of the checkiandj statement is completed, and checkiandj reiterates until its condition returns false. When false is returned, the program continues at the statement following checkiandj.

If continue had a label of checkiandj, the program would continue at the top of the checkiandj statement.

checkiandj : 
   while (i<4) {
      document.write(i + "<BR>");
      i+=1;
      checkj :
         while (j>4) {
            document.write(j + "<BR>");
            j-=1;
            if ((j%2)==0);
               continue checkj;
            document.write(j + " is odd.<BR>");
         }
      document.write("i = " + i + "<br>");
      document.write("j = " + j + "<br>");
   }

Object Manipulation Statements and Operators

JavaScript has several ways of manipulating objects: new operator, this keyword, for...in statement, and with statement.

new Operator

You can use the new operator to create an instance of a user-defined object type or of one of the predefined object types Array, Boolean, Date, Function, Image, Number, Object, Option, RegExp, or String. Use new as follows:

objectName = new objectType ( param1 [,param2] ...[,paramN] )
The following example creates an Array object with 25 elements, then assigns values to the first three elements:

musicTypes = new Array(25)
musicTypes[0] = "R&B"
musicTypes[1] = "Blues"
musicTypes[2] = "Jazz"
The following examples create several Date objects:

today = new Date()
birthday = new Date("December 17, 1995 03:24:00")
birthday = new Date(95,12,17)
The following example creates a user-define object type car, with properties for make, model, and year. The example then creates an object called mycar and assigns values to its properties. The value of mycar.make is the string "Eagle", mycar.year is the integer 1993, and so on.

function car(make, model, year) {
   this.make = make
   this.model = model
   this.year = year
}
mycar = new car("Eagle", "Talon TSi", 1993)
For more information on new, see the JavaScript Reference.

In Navigator 4.0, you can also create new objects using object initializers, as described in "Using Object Initializers".

this Keyword

Use the this keyword to refer to the current object. In general, this refers to the calling object in a method. Use this as follows:

this[.propertyName]
Example 1. Suppose a function called validate validates an object's value property, given the object and the high and low values:

function validate(obj, lowval, hival) {
   if ((obj.value < lowval) || (obj.value > hival))
      alert("Invalid Value!")
}
You could call validate in each form element's onChange event handler, using this to pass it the form element, as in the following example:

<B>Enter a number between 18 and 99:</B>
<INPUT TYPE = "text" NAME = "age" SIZE = 3
   onChange="validate(this, 18, 99)">
Example 2. When combined with the form property, this can refer to the current object's parent form. In the following example, the form myForm contains a Text object and a button. When the user clicks the button, the value of the Text object is set to the form's name. The button's onClick event handler uses this.form to refer to the parent form, myForm.

<FORM NAME="myForm">
Form name:<INPUT TYPE="text" NAME="text1" VALUE="Beluga">
<P>
<INPUT NAME="button1" TYPE="button" VALUE="Show Form Name"
   onClick="this.form.text1.value=this.form.name">
</FORM>

for...in Statement

The for...in statement iterates a specified variable over all the properties of an object. For each distinct property, JavaScript executes the specified statements. A for...in statement looks as follows:

for (variable in object) {
   statements }
Example. The following function takes as its argument an object and the object's name. It then iterates over all the object's properties and returns a string that lists the property names and their values.

function dump_props(obj, obj_name) {
   var result = ""
   for (var i in obj) {
      result += obj_name + "." + i + " = " + obj[i] + "<BR>"
   }
   result += "<HR>"
   return result
}
For an object car with properties make and model, result would be:

car.make = Ford
car.model = Mustang

with Statement

The with statement establishes the default object for a set of statements. Within the set of statements, any property references that do not specify an object are assumed to be for the default object. A with statement looks as follows:

with (object){
   statements
}
Example. The following with statement specifies that the Math object is the default object. The statements following the with statement refer to the PI property and the cos and sin methods, without specifying an object. JavaScript assumes the Math object for these references.

var a, x, y
var r=10
with (Math) {
   a = PI * r * r
   x = r * cos(PI)
   y = r * sin(PI/2)
}

Comments

Comments are author notations that explain what a script does. Comments are ignored by the interpreter. JavaScript supports Java-style comments:

Example. The following example shows two comments:

// This is a single-line comment.
/* This is a multiple-line comment. It can be of any length, and
you can put whatever you want here. */


[Contents] [Previous] [Next] [Index]

Last Updated: 11/26/97 09:26:02


Copyright 1997 Netscape Communications Corporation