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. The statements are:

The following sections provide a brief overview of each statement. See the statements reference for detailed information about statement syntax.


Conditional Statements

Conditional statements let you perform certain actions based on a logical condition. You specify a condition to test and the commands to execute if the condition is true. JavaScript has one conditional statement: the if statement.

if statement

An if statement is an either/or switch. If a specified condition is true, JavaScript performs certain statements. If the condition is false, JavaScript might perform other statements. 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 conditional statements can be any JavaScript statements, including further nested if statements. Multiple statements must be enclosed in 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} }

Loop Statements

A loop is a set of commands that executes repeatedly until a specified condition is met. JavaScript supports two loop structures: for and while. In addition, the break and continue statements are used specifically with loops.

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

for statement

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

for ([initial-expression;] [condition;] [increment-expression]) {
   statements
}

When a for loop is encountered, the initial-expression is executed. The statements are executed as long as condition evaluates to true. The increment-expression is performed on each pass through the loop. The sequence of execution is as follows:

  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 (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>

while statement

A while statement repeats a loop 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 only when the statements in the loop have been executed and the loop is about to be repeated. That is, the condition test is not continuous, but is performed once at the beginning of the loop and again just following the last statement in statements, each time control passes through the loop.

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 }

Each iteration, the loop increments n and adds it 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") }

break statement

The break statement terminates the current while or for loop and transfers program control to the statement following the terminated loop. A break statement looks as follows:

break

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

function testBreak(x) { var i = 0 while (i < 6) { if (i == 3) break i++ } return i*x }

continue statement

A continue statement terminates execution of the block of statements in a while or for loop, and continues execution of the loop with the next iteration. A continue statement looks as follows:

continue

In contrast to the break statement, continue does not terminate the execution of the loop entirely. Instead,

Example. The following example shows a while loop that has a continue statement that executes when the value of i is 3. Thus, n takes on the values 1, 3, 7, and 12.

i = 0 n = 0 while (i < 5) { i++ if (i == 3) continue n += i }

Object Manipulation Statements

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

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

new operator

The new operator lets you create an instance of a user-defined object type. Use new as follows:

objectName = new objectType ( param1 [,param2] ...[,paramN] )

For information, see new in the statements reference.

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. 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)">

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 notations by the author to 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. */