if...else and switchfor, while, do while, label, break, and continue (label is not itself a looping statement, but is frequently used with these statements)for...in and withtry...catch and throwif...else and switch.
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, {}.
Do not confuse the primitive Boolean values true and false with the true and false values of the Boolean object. Any object whose value is not undefined or null, including a Boolean object whose value is false, evaluates to true when passed to a conditional statement. For example:
var b = new Boolean(false);Example. In the following example, the function
if (b) // this condition evaluates to true
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 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>");
for, do while, while, and label loop statements (label is not itself a looping statement, but is frequently used with these statements). 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" on page 79.
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 ([initialExpression]; [condition]; [incrementExpression]) {
statements
}
When a for loop executes, the following occurs:
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.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.statements execute.incrementExpression executes, and control returns to Step 2.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 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 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 = 0With each iteration, the loop increments
x = 0
while( n < 3 ) {
n ++
x += n
}
n and adds that value to x. Therefore, x and n take on the following values:
n = 1 and x = 1
n = 2 and x = 3
n = 3 and x = 6
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 or continue statements to indicate whether a program should interrupt the loop or continue its execution.
The syntax of the label statement looks like the following:
label :The value of
statement
label may be any JavaScript identifier that is not a reserved word. The statement that you identify with a label may be any type.
Example. In this example, the label markLoop identifies a while loop.
markLoop:
while (theMark == true)
doSomething();
}
switch, or label statement.
break with a while, do-while, for, or switch statement, break terminates the innermost enclosing loop or switch immediately and transfers control to the following statement.break within an enclosing label statement, it terminates the statement and transfers control to the following statement. If you specify a label when you issue the break, the break statement terminates the specified statement.break statement looks like the following:
1. breakThe first form of the syntax terminates the innermost enclosing loop,
2. break [label]
switch, or label; the second form of the syntax terminates the specified enclosing label statement.
Example. The following example iterates through the elements in an array until it finds the index of an element whose value is theValue:
for (i = 0; i < a.length; i++) {
if (a[i] = theValue);
break;
}
continue statement can be used to restart a while, do-while, for, or label statement.
while or for statement, continue terminates the current loop and continues execution of the loop with the next iteration. In contrast to the break statement, continue does not terminate the execution of the loop entirely. In a while loop, it jumps back to the condition. In a for loop, it jumps to the increment-expression.label statement, continue is followed by a label that identifies a label statement. This type of continue restarts a label statement or continues execution of a labelled loop with the next iteration. continue must be in a looping statement identified by the label used by continue.continue statement looks like the following:
1. continueExample 1. The following example shows a
2. continue [label]
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 = 0Example 2. A statement labeled
n = 0
while (i < 5) {
i++
if (i == 3)
continue
n += i
}
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>");
}
for...in and with statements to manipulate objects.
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 = Fordwith statement establishes the default object for a set of statements. JavaScript looks up any unqualified names within the set of statements to determine if the names are properties of the default object. If an unqualified name matches a property, then the property is used in the statement; otherwise, a local or global variable is used.
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)
}
// 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. */
throw and try...catch statements.
You also use the try...catch statement to handle Java exceptions. See "Handling Java Exceptions in JavaScript" on page 141 and "Handling JavaScript Exceptions in Java" on page 144 for information.
throw statement to throw an exception. When you throw an exception, you specify an expression containing the value of the exception:
throw expressionThe following code throws several exceptions.
throw "Error2" // generates an exception with a string valueYou can specify an object when you throw an exception. You can then reference the object's properties in the
throw 42 // generates an exception with the value 42
throw true // generates an exception with the value true
catch block. The following example creates an object myUserException of type UserException and uses it in a throw statement.
// Create an object type UserException
function UserException (message) {
this.message=message
this.name="UserException"
}
// Create an instance of the object type and throw it
myUserException=new UserException("Value too high")
throw myUserException
try...catch statement marks a block of statements to try, and specifies a response should an exception be thrown. If an exception is thrown, the try...catch statement catches it.
The try...catch statement consists of a try block, which contains one or more statements, and a catch block, containing statements that specify what to do if an exception is thrown in the try block. That is, you want the try block to succeed, and if it does not succeed, you want control to pass to the catch block. If any statement within the try block (or in a function called from within the try block) throws an exception, control immediately shifts to the catch block. If no exception is thrown in the try block succeed, the catch block is skipped. The finally block executes after the try and catch blocks execute but before the statements following the try...catch statement.
The following example uses a try...catch statement. The example calls a function that retrieves a month name from an array based on the value passed to the function. If the value does not correspond to a month number (1-12), an exception is thrown with the value "InvalidMonthNo" and the statements in the catch block set the monthName variable to "unknown".
function getMonthName (mo) {
mo=mo-1 // Adjust month number for array index (1=Jan, 12=Dec)
var months=new Array("Jan","Feb","Mar","Apr","May","Jun","Jul",
"Aug","Sep","Oct","Nov","Dec")
if (months[mo] != null) {
return months[mo]
} else {
throw "InvalidMonthNo"
}
}try {
// statements to try
monthName=getMonthName(myMonth) // function could throw exception
}
catch (e) {
monthName="unknown"
logMyErrors(e) // pass exception object to error handler
}
try...catch statement's catch block (recovery block) to execute error-handling code.
A catch block looks as follows:
catch (catchID) {
statements
}
Every catch block specifies an identifier (catchID in the preceding syntax) that holds the value specified by the throw statement; you can use this identifier to get information about the exception that was thrown. JavaScript creates this identifier when the catch block is entered; the identifier lasts only for the duration of the catch block; after the catch block finishes executing, the identifier is no longer available.
For example, the following code throws an exception. When the exception occurs, control transfers to the catch block.
try {
throw "myException" // generates an exception
}
catch (e) {
// statements to handle any exceptions
logMyErrors(e) // pass exception object to error handler
}
finally block contains statements to execute after the try and catch blocks execute but before the statements following the try...catch statement. The finally block executes whether or not an exception is thrown. If an exception is thrown, the statements in the finally block execute even if no catch block handles the exception.
You can use the finally block to make your script fail gracefully when an exception occurs; for example, you may need to release a resource that your script has tied up. The following example opens a file and then executes statements that use the file (server-side JavaScript allows you to access files). If an exception is thrown while the file is open, the finally block closes the file before the script fails.
try {
openMyFile() // tie up a resource
writeMyFile(theData)
}
finally {
closeMyFile() // always close the resource
}
try...catch statements. If an inner try...catch statement does not have a catch block, the enclosing try...catch statement's catch block is checked for a match.
Last Updated: 10/29/98 15:51:07