12.7. Control Statements
Stops execution of the current loop and returns control to the next
script statement following the end of the current loop. Note that
without a label parameter, the scope of the
break
statement is its own loop. To break out of a nested loop, assign
labels to each nested layer, and use the desired label as a parameter
with the
break statement. See the
label statement (available only starting with
Navigator 4 and Internet Explorer 4).
Syntax
break [label]
Example
See the label statement.
Stops execution of the current iteration through the loop and returns
to the top of the loop for the next pass (executing the update
expression if one is specified in a
for loop). If
you are using nested loop constructions, assign labels to each nested
layer, and use the desired label as a parameter with the
continue statement. See the
label statement (available only starting with
Navigator 4 and Internet Explorer 4).
Syntax
continue [label]
Example
outerLoop:
for (var i = 0; i <= maxValue1; i++) {
for (var j = 0; j <= maxValue2; j++) {
if (j*i == magic2) {
continue outerLoop;
}
}
}
Executes statements in a loop while a condition is true. Because the
condition is tested at the end of the loop, the statements inside it
are always executed at least one time. It is imperative that the
expression that makes up the condition have some aspect of its value
potentially altered in the statements. Otherwise, an infinite loop
occurs.
Syntax
do {
statements
} while (condition)
Example
var i = 1;
do {
window.status = "Loop number " + i++;
} while (i <= 10)
window.status = "";
This is a construction that allows repeated execution of statements,
usually for a controlled number of times.
Syntax
for ([initExpression]; [condition]; [updateExpression]) {
statements
}
Example
var userEntry = document.forms[0].entry.value;
var oneChar;
for (var i = 0; i < userEntry.length; i++) {
oneChar = userEntry.charAt(i);
if (oneChar < "0" || oneChar > "9") {
alert("The entry must be numerals only.");
}
}
This is a variation of the regular
for loop that
can extract the property names and values of an object. Only
properties (and, in Netscape 6, methods) that are set to be
enumerable by the browser internals appear in the output of this
construction. Opera 6 supports this construction only for custom
script-generated objects.
Syntax
for (varName in objectRef) {
statements
}
Example
function showProps( ) {
objName = "image";
obj = document.images[0];
var msg = "";
for (var i in obj) {
msg += objName + "." + i + "=" + obj[i] + "\n";
}
alert(msg);
}
This is a simple conditional statement that provides one alternate
execution path.
Syntax
if (condition) {
statement(s) if true
}
Example
if (myDateObj.getMonth( ) == 1) {
calcMonthLength( );
}
This is a conditional statement that provides two execution paths
depending on the result of the condition. You can nest another
if or
if/
else statement inside either
path of the
if/
else statement.
Syntax
if (condition) {
statement(s) if true
} else {
statement(s) if false
}
Example
var theMonth = myDateObj.getMonth( );
if (theMonth == 1) {
monLength = calcLeapMonthLength( );
} else {
monLength = calcMonthLength(theMonth);
}
You can assign a label identifier to any block of executing
statements, including control structures. The purpose of the label is
to allow
break and
continue
statements within deeply nested control structures to exit to a
nested level that may be at levels beyond the scope of the normal
break and
continue statements.
Syntax
labelName:
Example
outerLoop:
for (var i = 0; i <= maxValue1; i++) {
for (var j = 0; j <= maxValue2; j++) {
if (i == magic1 && j == magic2) {
break outerLoop;
}
}
}
Stops execution of the current function. A
return
statement can be located anywhere within the function, including
inside control structures. You can optionally specify a value to be
returned to the calling statement. This return value can be any
JavaScript data type. If a
return statement that
returns a value is in a loop or other control structure, there must
be a
return statement for each branch of the
execution tree, including a default
return
statement if execution should reach the main execution scope near or
at the end of the function.
Syntax
return [value]
Example
function validateNumber(form) {
var oneChar;
for (var i = 0; i < userEntry.length; i++) {
oneChar = form.entry.value.charAt(i);
if (oneChar < "0" || oneChar > "9") {
return false;
}
}
return true;
}
switch/case | NN 4 IE 4 ECMA 3 |
Provides a shortcut to execution paths for numerous conditions of an
expression. The optional
break statement at the
end of each
case block shortcuts execution of the
switch statement, and also prevents the
inadvertent execution of the
default block, if
present.
Syntax
switch (expression) {
case label1:
statements
[break;]
case label2:
statements
[break;]
...
[default:
statements]
}
Example
var productList = document.forms[0].prodList;
var chosenItem = productList.options[productList.selectedIndex].value;
switch(chosenItem) {
case "Small Widget":
document.forms[0].price.value = "44.95";
break;
case "Medium Widget":
document.forms[0].price.value = "54.95";
break;
case "Large Widget":
document.forms[0].price.value = "64.95";
break;
default:
document.forms[0].price.value = "Nothing Selected";
}
Triggers an exception condition, passing a value along with the
exception. Although the value you pass can be a simple string,
ideally you should pass an instance of the JavaScript
Error object filled with sufficient information
for a catch statement to act intelligently on the error. A
throw statement must be enclosed in the
try portion of a
try-catch
construction.
Syntax
throw value;
Example
function processNumber(inputField) {
try {
var inpVal = parseInt(inputField.value, 10);
if (isNaN(inpVal)) {
var msg = "Please enter a number only.";
var err = new Error(msg);
if (!err.message) {
err.message = msg;
}
throw err;
}
// process number
}
catch (e) {
alert(e.message);
inputField.focus( );
inputField.select( );
}
}
try/catch | NN 6 IE 5 ECMA 3 |
This construction provides a nondisruptive way to trap for errors
(exceptions) and handle them gracefully. Both parts of this
exception-handling construction are required. If an error occurs in
the
try portion, execution immediately branches to
the
catch portion, where your scripts can display
alert dialogs, modify data, or any other task that keeps the
JavaScript interpreter from triggering a disruptive error message.
Exceptions that occur naturally (i.e., they are not thrown by a
throw statement) pass an instance of the
Error object as a parameter to the
catch section. Statements inside the
catch section can examine properties of the error
object to determine how to handle exceptions that land there. Thus,
one
catch portion can handle errors of various
types.
You can use try/catch
constructions only in browsers that support them. To protect older
browsers from seeing this construction, place all affected code
inside a <script> tag that explicitly requires JavaScript 1.5
or later (with the language = "JavaScript1.5"
attribute.
Syntax
try {
statement(s) that could cause error
}
catch (errorInfo) {
process error(s) gracefully
}
Example
function insertOneNode(baseNode, newNode, position) {
try {
baseNode.insertBefore(newNode, baseNode.childNodes[position]);
}
catch (e) {
// handle W3C DOM Exception types
switch (e.name) {
case "HIERARCHY_REQUEST_ERR" :
// process bad tree hierarchy reference
break;
case "NOT_FOUND_ERR" :
// process bad refNode reference
break;
default :
// process all other exceptions
}
}
return true;
}
Executes statements in a loop as long as a condition is true. Because
the condition is tested at the beginning of the loop, it is
conceivable that under the right conditions, the statements inside
the loop do not execute. It is imperative that the expression that
makes up the condition have some aspect of its value potentially
altered in the statements. Otherwise an infinite loop occurs.
Syntax
while (condition) {
statements
}
Example
var i = 0;
while (!document.forms[0].radioGroup[i].checked) {
i++;
}
alert("You selected item number " + (i+1) + ".");
The
with statement adds an object to the scope of
every statement nested within. This can shorten the code of some
statement groups that rely on a particular object reference. Note
that
with constructions are generally very
inefficient. You can achieve better performance by assigning the
object reference to a local variable, and using that variable in your
function.
Syntax
with (objectRef) {
statements
}
Example
with (document.forms[0]) {
name1 = firstName.value;
name2 = lastName.value;
mail = eMail.value;
}
| | |
12.6. Operators | | 12.8. Miscellaneous Statements |
Copyright © 2003 O'Reilly & Associates. All rights reserved.