| Chapter 3 StatementsThis 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 { }.Table 3.1 lists statements available in JavaScript.Table 3.1 JavaScript statements. break
| Statement that 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
| Statement that terminates execution of the block of statements in a while or for loop, and continues execution of the loop with the next iteration. | delete
| Deletes an object's property or an element of an array. | do...while
| Executes its statements until the test condition evaluates to false. Statement is executed at least once. | export
| Allows a signed script to provide properties, functions, and objects to other signed or unsigned scripts. | for
| Statement that 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
| Statement that iterates a specified variable over all the properties of an object. For each distinct property, JavaScript executes the specified statements. | function
| Statement that declares a JavaScript function name with the specified parameters. Acceptable parameters include strings, numbers, and objects. | if...else
| Statement that 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 which has exported the information. | labeled
| Provides an identifier that can be used with break or continue to indicate where the program should continue execution. | return
| Statement that 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. | var
| Statement that declares a variable, optionally initializing it to a value. | while
| Statement that creates a loop that evaluates an expression, and if it is true, executes a block of statements. | with
| Statement that establishes the default object for a set of statements. |
breakTerminates the current while or for loop and transfers program control to the statement following the terminated loop.
Implemented in | Navigator 2.0, LiveWire 1.0 |
Syntaxbreak break label Argument
label | Identifier associated with the label of the statement. |
DescriptionThe break statement can now include an optional label that allows the program to break out of a labeled statement. This type of break must be in a statement identified by the label used by break. The statements in a labeled statement can be of any type. ExamplesThe 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 } 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 alsolabeled , switch
commentNotations by the author to explain what a script does. Comments are ignored by the interpreter.
Implemented in | Navigator 2.0, LiveWire 1.0 |
Syntax// comment text /* multiple line comment text */ DescriptionJavaScript supports Java-style comments:- Comments on a single line are preceded by a double-slash (//).
- Comments that span multiple lines are preceded by a /* and followed by a */.
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. */
continueTerminates execution of the block of statements in a while or for loop, and continues execution of the loop with the next iteration.
Implemented in | Navigator 2.0, LiveWire 1.0 |
Syntaxcontinue continue label Argument
label | Identifier associated with the label of the statement. |
DescriptionIn contrast to the break statement, continue does not terminate the execution of the loop entirely: instead,- In a
while loop, it jumps back to the condition .
- In a
for loop, it jumps to the update expression.
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 . ExamplesThe 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 } 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 alsolabeled
deleteDeletes an object's property or an element at a specified index in an array.
Implemented in | Navigator 4.0, Netscape Server 3.0 |
Syntaxdelete objectName.property delete objectName[index] delete property Arguments
objectName | An object from which to delete the specified property or value. | property | The property to delete. | index | An integer index into an array. |
DescriptionIf the delete operator succeeds, it sets the property of element to undefined ; the operator always returns undefined .You can only use the delete operator to delete object properties and array entries. You cannot use this operator to delete objects or variables. Consequently, you can only use the third form within a with statement, to delete a property from the object.
do...while Executes its statements until the test condition evaluates to false. Statement is executed at least once.
Implemented in | Navigator 4.0, Netscape Server 3.0 |
Syntaxdo statement while (condition); Arguments
statement | 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 . |
ExampleIn 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);
exportAllows a signed script to provide properties, functions, and objects to other signed or unsigned scripts.
Implemented in | Navigator 4.0, Netscape Server 3.0 |
Syntaxexport name1, name2, ..., nameN export * Parameters
nameN | List of properties, functions, and objects to be exported. | * | Exports all properties, functions, and objects from the script. |
DescriptionTypically, 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 alsoimport
forCreates 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 | Navigator 2.0, LiveWire 1.0 |
Syntaxfor ([initial-expression;] [condition;] [increment-expression]) { statements } Arguments
initial-expression | Statement or variable declaration. Typically used to initialize a counter variable. This expression may optionally declare new variables with the var keyword. | 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. |
ExamplesThe 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...inIterates a specified variable over all the properties of an object. For each distinct property, JavaScript executes the specified statements.
Implemented in | Navigator 2.0, LiveWire 1.0 |
Syntaxfor (variable in object) { statements} Arguments
variable | Variable to iterate over every property. | object | Object for which the properties are iterated. | statements | Specifies the statements to execute for each property. |
ExamplesThe 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, objName) { var result = "" for (var i in obj) { result += objName + "." + i + " = " + obj[i] + "<BR>" } result += "<HR>" return result }
functionDeclares a JavaScript function with the specified parameters. Acceptable parameters include strings, numbers, and objects.
Implemented in | Navigator 2.0, LiveWire 1.0 |
Syntaxfunction name([param] [, param] [..., param]) { statements} Arguments
name | The function name. | param | The name of an argument to be passed to the function. A function can have up to 255 arguments. |
DescriptionTo return a value, the function must have a return statement that specifies the value to return. You cannot nest a function statement in another statement or in itself.All parameters are passed to functions, by value. In other words, the value is passed to the function, but if the function changes the value of the parameter, this change is not reflected globally or in the calling function.In addition to defining functions as described here, you can also define Function objects. Examples//This function 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 }
if...elseExecutes a set of statements if a specified condition is true. If the condition is false, another set of statements can be executed.
Implemented in | Navigator 2.0, LiveWire 1.0 |
Syntaxif (condition) { statements1} [else { statements2}] Arguments
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. |
Examplesif (cipher_char == from_char) { result = result + to_char x++} else result = result + clear_char
importAllows a script to import properties, functions, and objects from a signed script which has exported the information.
Implemented in | Navigator 4.0, Netscape Server 3.0 |
Syntaximport objectName.name1, objectName.name2, ..., objectName.nameN import objectName.* Parameters
nameN | List of properties, functions, and objects to import from the export file. | objectName | Name of the object that will receive the imported names. | * | imports all properties, functions, and objects from the export script. |
DescriptionThe 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, thenimport obj.f, obj.p makes f and p accessible in the importing script as properties of obj . 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 alsoexport
labeled Provides an identifier that can be used with break or continue to indicate where the program should continue execution.
Implemented in | Navigator 4.0, Netscape Server 3.0 | 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 . Syntaxlabel : statement Arguments
statement | Block of statements. break can be used with any labeled statement, and continue can be used with looping labeled statements. |
ExampleFor an example of a labeled statement using break , see break . For an example of a labeled statement using continue , see continue . See alsobreak , continue
returnSpecifies the value to be returned by a function.
Implemented in | Navigator 2.0, LiveWire 1.0 |
Syntaxreturn expression ExamplesThe 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 | Navigator 4.0, Netscape Server 3.0 |
Syntaxswitch (expression){ case label : statement; break; case label : statement; break; ... default : statement; } Arguments
expression | Value matched against label. | label | Identifier used to match against expression. | statement | Any statement. |
DescriptionIf a match is found, the program executes the associated 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. ExampleIn 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>");
varDeclares a variable, optionally initializing it to a value.
Implemented in | Navigator 2.0, LiveWire 1.0 |
Syntaxvar varname [= value] [..., varname [= value] ] Arguments
varname | Variable name. It can be any legal identifier. | value | Initial value of the variable and can be any legal expression. |
DescriptionThe 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 if a global variable of the same name exists. Examplesvar num_hits = 0, cust_no = 0
whileCreates 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 | Navigator 2.0, LiveWire 1.0 |
Syntaxwhile (condition) { statements } Arguments
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. |
ExamplesThe 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 the first pass: n = 1 and x = 1
- After the second pass: n = 2 and x = 3
- After the third pass: n = 3 and x = 6
After completing the third pass, the condition n < 3 is no longer true, so the loop terminates.
withEstablishes 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.
Implemented in | Navigator 2.0, LiveWire 1.0 |
Syntaxwith (object){ statements } Arguments
object | Specifies the default object to use for the statements. The parentheses around object are required. | statements | Any block of statements. |
ExamplesThe 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) } |
| |