Table of Contents | Previous | Next | Index


Chapter 3
Statements

This chapter describes all JavaScript statements. JavaScript statements consist of keywords used with the appropriate syntax. A single statement may span multiple lines. Multiple statements may occur on a single line if each statement is separated by a semicolon.

Syntax conventions: All keywords in syntax statements are in bold. Words in italics represent user-defined names or statements. Any portions enclosed in square brackets, [ ], are optional. {statements} indicates a block of statements, which can consist of a single statement or multiple statements delimited by a curly braces { }.

The following table lists statements available in JavaScript.

Table 3.1 JavaScript statements.  
break

Terminates the current while or for loop and transfers program control to the statement following the terminated loop.

comment

Notations by the author to explain what a script does. Comments are ignored by the interpreter.

continue

Terminates execution of the block of statements in a while or for loop, and continues execution of the loop with the next iteration.

do...while

Executes the specified statements until the test condition evaluates to false. Statements execute at least once.

export

Allows a signed script to provide properties, functions, and objects to other signed or unsigned scripts.

for

Creates a loop that consists of three optional expressions, enclosed in parentheses and separated by semicolons, followed by a block of statements executed in the loop.

for...in

Iterates a specified variable over all the properties of an object. For each distinct property, JavaScript executes the specified statements.

function

Declares a function with the specified parameters. Acceptable parameters include strings, numbers, and objects.

if...else

Executes a set of statements if a specified condition is true. If the condition is false, another set of statements can be executed.

import

Allows a script to import properties, functions, and objects from a signed script that has exported the information.

label

Provides an identifier that can be used with break or continue to indicate where the program should continue execution.

return

Specifies the value to be returned by a function.

switch

Allows a program to evaluate an expression and attempt to match the expression's value to a case label.

throw

Throws a user-defined exception.

try...catch

Marks a block of statements to try, and specifies a response should an exception be thrown.

var

Declares a variable, optionally initializing it to a value.

while

Creates a loop that evaluates an expression, and if it is true, executes a block of statements. The loop then repeats, as long as the specified condition is true.

with

Establishes the default object for a set of statements.


break

Use the break statement to terminate a loop, switch, or label statement.

Terminates the current loop, switch, or label statement and transfers program control to the statement following the terminated loop.

Implemented in

JavaScript 1.0, NES 2.0

ECMA version

ECMA-262

Syntax

break [label]

Parameter

label

Identifier associated with the label of the statement.

Description

The break statement includes an optional label that allows the program to break out of a labeled statement. The statements in a labeled statement can be of any type.

Examples

Example 1. The following function has a break statement that terminates the while loop when e 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
}
Example 2. In the following 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>");
   }

See also

continue, label, switch


comment

Notations by the author to explain what a script does. Comments are ignored by the interpreter.

Implemented in

JavaScript 1.0, NES 2.0

ECMA version

ECMA-262

Syntax

// comment text
/* multiple line comment text */

Description

JavaScript supports Java-style comments:

Examples

// 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. */

continue

Restarts a while, do-while, for, or label statement.

Implemented in

JavaScript 1.0, NES 2.0

ECMA version

ECMA-262

Syntax

continue [label]

Parameter

label

Identifier associated with the label of the statement.

Description

In contrast to the break statement, continue does not terminate the execution of the loop entirely: instead,

The continue statement can now include an optional label that allows the program to terminate execution of a labeled statement and continue to the specified labeled statement. This type of continue must be in a looping statement identified by the label used by continue.

Examples

Example 1. 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
}
Example 2. In the following example, a statement labeled checkiandj contains a statement labeled checkj. If continue is encountered, the program continues at the top of the checkj statement. Each time continue is encountered, checkj reiterates until its condition returns false. When false is returned, the remainder of the checkiandj statement is completed. 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>");
}

See also

break, label


do...while

Executes the specified statements until the test condition evaluates to false. Statements execute at least once.

Implemented in

JavaScript 1.2, NES 3.0

Syntax

do 
   statements
while (condition);

Parameters

statements

Block of statements that is executed at least once and is re-executed each time the condition evaluates to true.

condition

Evaluated after each pass through the loop. If condition evaluates to true, the statements in the preceding block are re-executed. When condition evaluates to false, control passes to the statement following do while.

Examples

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);

export

Allows a signed script to provide properties, functions, and objects to other signed or unsigned scripts.

Implemented in

JavaScript 1.2, NES 3.0

Syntax

export name1, name2, ..., nameN
export *

Parameters

nameN

List of properties, functions, and objects to be exported.

*

Exports all properties, functions, and objects from the script.

Description

Typically, information in a signed script is available only to scripts signed by the same principals. By exporting properties, functions, or objects, a signed script makes this information available to any script (signed or unsigned). The receiving script uses the companion import statement to access the information.

See also

import


for

Creates a loop that consists of three optional expressions, enclosed in parentheses and separated by semicolons, followed by a block of statements executed in the loop.

Implemented in

JavaScript 1.0, NES 2.0

ECMA version

ECMA-262

Syntax

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

Parameters

initial-expression

Statement or variable declaration. Typically used to initialize a counter variable. This expression may optionally declare new variables with the var keyword. These variables are local to the function, not to the loop.

condition

Evaluated on each pass through the loop. If this condition evaluates to true, the statements in statements are performed. This conditional test is optional. If omitted, the condition always evaluates to true.

increment-expression

Generally used to update or increment the counter variable.

statements

Block of statements that are executed as long as condition evaluates to true. This can be a single statement or multiple statements. Although not required, it is good practice to indent these statements from the beginning of the for statement.

Examples

The following for statement starts by declaring the variable i and initializing it to 0. It checks that i is less than nine, performs the two succeeding statements, and increments i by 1 after each pass through the loop.

for (var i = 0; i < 9; i++) {
   n += i
   myfunc(n)
}

for...in

Iterates a specified variable over all the properties of an object. For each distinct property, JavaScript executes the specified statements.

Implemented in

JavaScript 1.0, NES 2.0

ECMA version

ECMA-262

Syntax

for (variable in object) {
   statements
}

Parameters

variable

Variable to iterate over every property, declared with the var keyword. This variable is local to the function, not to the loop.

object

Object for which the properties are iterated.

statements

Specifies the statements to execute for each property.

Examples

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 show_props(obj, objName) {
   var result = ""
   for (var i in obj) {
      result += objName + "." + i + " = " + obj[i] + "\n"
   }
   return result
}

function

Declares a function with the specified parameters. Acceptable parameters include strings, numbers, and objects.

Implemented in

JavaScript 1.0, NES 2.0

ECMA version

ECMA-262

Syntax

function name([param] [, param] [..., param]) {
   statements
}
You can also define functions using the Function constructor; see "Function" on page 79.

Parameters

name

The function name.

param

The name of an argument to be passed to the function. A function can have up to 255 arguments.

statements

The statements which comprise the body of the function.

Description

To return a value, the function must have a return statement that specifies the value to return.

A function created with the function statement is a Function object and has all the properties, methods, and behavior of Function objects. See "Function" on page 79 for detailed information on functions.

Examples

The following code declares a function that returns the total dollar amount of sales, when given the number of units sold of products a, b, and c.

function calc_sales(units_a, units_b, units_c) {
   return units_a*79 + units_b*129 + units_c*699
}

See also

"Function" on page 79


if...else

Executes a set of statements if a specified condition is true. If the condition is false, another set of statements can be executed.

Implemented in

JavaScript 1.0, NES 2.0

ECMA version

ECMA-262

Syntax

if (condition) {
   statements1
}
[else {
   statements2
}]

Parameters

condition

Can be any JavaScript expression that evaluates to true or false. Parentheses are required around the condition. If condition evaluates to true, the statements in statements1 are executed.

statements1,
statements2

Can be any JavaScript statements, including further nested if statements. Multiple statements must be enclosed in braces.

Description

You should not use simple assignments in a conditional statement. For example, do not use the following code:

if(x = y)
{
   /* do the right thing */
}
If you need to use an assignment in a conditional statement, put additional parentheses around the assignment. For example, use if( (x = y) ).

Backward Compatibility

JavaScript 1.2 and earlier versions. You can use simple assignments in a conditional statement. An assignment operator in a conditional statement is converted to an equality operator. For example, if(x = y) is converted to if(x == y).

Examples

if (cipher_char == from_char) {
   result = result + to_char
   x++}
else
   result = result + clear_char

import

Allows a script to import properties, functions, and objects from a signed script that has exported the information.

Implemented in

JavaScript 1.2, NES 3.0

Syntax

import objectName.name1, objectName.name2, ..., objectName.nameN
import objectName.*

Parameters

objectName

Name of the object that will receive the imported names.

name1,
name2,
nameN

List of properties, functions, and objects to import from the export file.

*

Imports all properties, functions, and objects from the export script.

Description

The objectName parameter is the name of the object that will receive the imported names. For example, if f and p have been exported, and if obj is an object from the importing script, the following code makes f and p accessible in the importing script as properties of obj.

import obj.f, obj.p
Typically, information in a signed script is available only to scripts signed by the same principals. By exporting (using the export statement) properties, functions, or objects, a signed script makes this information available to any script (signed or unsigned). The receiving script uses the import statement to access the information.

The script must load the export script into a window, frame, or layer before it can import and use any exported properties, functions, and objects.

See also

export


label

Provides a statement with an identifier that lets you refer to it elsewhere in your program.

Implemented in

JavaScript 1.2, NES 3.0

For example, you can use a label to identify a loop, and then use the break or continue statements to indicate whether a program should interrupt the loop or continue its execution.

Syntax

label :
   statements

Parameter

label

Any JavaScript identifier that is not a reserved word.

statements

Block of statements. break can be used with any labeled statement, and continue can be used with looping labeled statements.

Examples

For an example of a label statement using break, see break. For an example of a label statement using continue, see continue.

See also

break, continue


return

Specifies the value to be returned by a function.

Implemented in

JavaScript 1.0, NES 2.0

ECMA version

ECMA-262

Syntax

return expression

Parameters

expression

The expression to return.

Examples

The following function returns the square of its argument, x, where x is a number.

function square(x) {
   return x * x
}

switch

Allows a program to evaluate an expression and attempt to match the expression's value to a case label.

Implemented in

JavaScript 1.2, NES 3.0

Syntax

switch (expression){
   case label :
      statements;
      break;
   case label :
      statements;
      break;
   ...
   default : statements;
}

Parameters

expression

Value matched against label.

label

Identifier used to match against expression.

statements

Block of statements that is executed once if expression matches label.

Description

If a match is found, the program executes the associated statement. If multiple cases match the provided value, the first case that matches is selected, even if the cases are not equal to each other.

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.

Examples

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

switch (i) {
   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>");

throw

Throws a user-defined exception.

Implemented in

JavaScript 1.4

Syntax

throw expression

Parameters

expression

The value to throw.

Description

Use the throw statement to throw an exception. When you throw an exception, an expression specifies the value of the exception. The following code throws several exceptions.

throw "Error2"    // generates an exception with a string value
throw 42          // generates an exception with the value 42
throw true        // generates an exception with the value true

Examples

Example 1: Throw an object. You can specify an object when you throw an exception. You can then reference the object's properties in the catch block. The following example creates an object myUserException of type UserException and uses it in a throw statement.

function UserException (message) {
   this.message=message
   this.name="UserException"
}
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 {
      myUserException=new UserException("InvalidMonthNo")
      throw myUserException
   }
}
try {
   // statements to try
   monthName=getMonthName(myMonth)
}
catch (e) {
   monthName="unknown"
   logMyErrors(e.message,e.name) // pass exception object to err handler
}
Example 2: Throw an object. The following example tests an input string for a U.S. zip code. If the zip code uses an invalid format, the throw statement throws an exception by creating an object of type ZipCodeFormatException.

/*
 * Creates a ZipCode object.
 *
 * Accepted formats for a zip code are:
 *    12345
 *    12345-6789
 *    123456789
 *    12345 6789
 *
 * If the argument passed to the ZipCode constructor does not
 * conform to one of these patterns, an exception is thrown.
 */
function ZipCode(zip) {
   zip = new String(zip);
   pattern = /[0-9]{5}([- ]?[0-9]{4})?/;
   if (pattern.test(zip)) {
      // zip code value will be the first match in the string
      this.value = zip.match(pattern)[0]
      this.valueOf = new Function("return this.value");
      this.toString = new Function("return String(this.value)");
   } else {
      throw new ZipCodeFormatException(zip);
   }
}
function ZipCodeFormatException(value) {
   this.value = value;
   this.message =
      "does not conform to the expected format for a zip code";
   this.toString =
      new Function("return this.value +\":\" + this.message");
}
/*
 * This could be in a script that validates address data
 * for US addresses.
 */
var ZIPCODE_INVALID = -1;
var ZIPCODE_UNKNOWN_ERROR = -2;
function verifyZipCode(z) {
   try {
      z = new ZipCode(z);
   }
   catch (e) {
      if (e instanceof ZipCodeFormatException) {
         return ZIPCODE_INVALID;
      }
      else {
         return ZIPCODE_UNKNOWN_ERROR;
      }
   }
   return z;
}
a=verifyZipCode(95060)         // returns 95060
b=verifyZipCode(9560)          // returns -1
c=verifyZipCode("a")           // returns -1
d=verifyZipCode("95060")       // returns 95060
e=verifyZipCode("95060 1234")  // returns 95060 1234
Example 3: Rethrow an exception. You can use throw to rethrow an exception after you catch it. The following example catches an exception with a numeric value and rethrows it if the value is over 50. The rethrown exception propagates up to the enclosing function or to the top level so that the user sees it.

try {
   throw n // throws an exception with a numeric value
}
catch (e) {
   if (e <= 50) {
      // statements to handle exceptions 1-50
   }
   else {
      // cannot handle this exception, so rethrow
      throw e
   }
}

See also

try...catch


try...catch

Marks a block of statements to try, and specifies a response should an exception be thrown.

Implemented in

JavaScript 1.4

Syntax

try {
   statements
}
[catch (catchID) {
   statements
}]
[finally {
   statements
}]

Parameters

statements

Block of statements that executes once. The statements can be declarative statements (such as var) or executable statements (such as for).

catch

A block of statements to be executed if an exception is thrown in the try block.

catchID

An identifier to hold an exception object.

finally

A block of statements that is executed before the try...catch statement completes. This block of statements executes whether or not an exception was thrown or caught.

Description

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.

You can nest one or more try...catch statements. If an inner try...catch statement does not have a catch block, the enclosing try...catch statement's catch block is entered.

You also use the try...catch statement to handle Java exceptions. See the Core JavaScript Guide for information on Java exceptions.

The catch Block. The catch block is entered when any exception is thrown. 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
}
The catch Block's Identifier. When an exception is thrown in the try block, the catchID 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.

The finally Block. The 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
}

Examples

See the examples for throw.

See also

throw


var

Declares a variable, optionally initializing it to a value.

Implemented in

JavaScript 1.0, NES 2.0

ECMA version

ECMA-262

Syntax

var varname [= value] [..., varname [= value] ]

Parameters

varname

Variable name. It can be any legal identifier.

value

Initial value of the variable and can be any legal expression.

Description

The scope of a variable is the current function or, for variables declared outside a function, the current application.

Using var outside a function is optional; you can declare a variable by simply assigning it a value. However, it is good style to use var, and it is necessary in functions in the following situations:

Examples

var num_hits = 0, cust_no = 0

while

Creates a loop that evaluates an expression, and if it is true, executes a block of statements. The loop then repeats, as long as the specified condition is true.

Implemented in

JavaScript 1.0, NES 2.0

ECMA version

ECMA-262

Syntax

while (condition) {
   statements
}

Parameters

condition

Evaluated before each pass through the loop. If this condition evaluates to true, the statements in the succeeding block are performed. When condition evaluates to false, execution continues with the statement following statements.

statements

Block of statements that are executed as long as the condition evaluates to true. Although not required, it is good practice to indent these statements from the beginning of the statement.

Examples

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.


with

Establishes the default object for a set of statements.

Implemented in

JavaScript 1.0, NES 2.0

ECMA version

ECMA-262

Syntax

with (object){
   statements
}

Parameters

object

Specifies the default object to use for the statements. The parentheses around object are required.

statements

Any block of statements.

Description

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.

Examples

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)
}

Table of Contents | Previous | Next | Index

Last Updated: 10/29/98 20:17:41

Copyright (c) 1998 Netscape Communications Corporation