The break statement immediately terminates an ongoing for or while loop.
Syntax
The syntax for the break statement is
break
Description
The break statement can be used only within the curly braces ({ }) following a for or while loop. When executed, break terminates the loop and passes execution to the first statement after the loop's closing curly brace (}).
Example
The custom contains() function that follows looks at each character in a string (lstring). If it finds a character that matches the character stored in onechar, it sets the variable retval to true and stops looking.
function contains(onechar,lstring) {
retval = false
for (var i=1;i<=lstring.length;i++) {
if (lstring.substring(i,i+1)==onechar) {
retval=true break
}
}
return retval
}
The continue statement terminates the remaining statements in a for or while loop and continues execution at the top of the loop (the next iteration of the loop).
Syntax
The syntax for this statement is
continue
Description
The continue statement makes sense only within the curly braces of a for or while loop. Unlike the break statement, continue passes control back to the top of the loop. It does not terminate the loop. In a for loop, continue jumps back to and executes the increment-expression. In a while loop, continue jumps back to and evaluates the condition statement.
Example
Opening the following page
<HTML>
<BODY>
<SCRIPT Language = "JavaScript">
i=0
while (i < 10) {
i++
if (i/3 == parseInt(i/3)){
continue
}
document.write ("i=",i,"<BR>")
}
</SCRIPT>
</BODY>displays this on the Web browser screen.
Numbers that are evenly divisible by three (3, 6, 9) are omitted because the if() statement in the while loop forces the loop to start over, without getting to the document.write() statement, when the value of i is evenly divisible by 3.
The for statement defines a loop that repeats a series of commands as long as some condition holds true.
Syntax
The syntax for statements is ([intial-expression;] [condition;] [increment-expression]) { statements }
where intial-expression is an expression that sets the starting value, condition is an expression that proves true or false, increment-expression is an expression that incrememts the initial expression, and statements are Javascript statements that are executed with each pass through the loop as long as condition proves true.
Description
The for loop is generally used to set up a loop and create a counter that is incremented with each pass through the loop. The intial-expression is evaluated first, followed by the condition. If the condition proves true, then all statements within the curly braces that follow are executed once. Next, the increment-expression is executed and the condition is re-tested. When the condition proves false, the loop terminates and execution resumes just after the closing curly brace (}).
Example
When this Web page is opened in a browser
<HTML>
<BODY>
<SCRIPT Language = "JavaScript">
for (var i=1; i <= 10; i++) {
document.write ('i = ',i,'<br>')
}
</SCRIPT>
</BODY>
</HTML>it displays:
because for each pass through the loop, the document.write statement writes "i = " followed by the current value of i. It then i++ increments the value in i by 1 and the loop continues as long as i is less than or equal to 10.
The for...in statement iterates a value over all properties of an object.
Syntax
The syntax for this statement is for (variable in object) { statements }
where variable is any valid variable name, object is the name of any existing object, and statements are Javascript statements that are executed as long as variable is less than or equal to the number of properties assigned to an object.
Description
All objects have properties. The for...in loop can get at those properties without using specific property names. For example, if i is the variable defined in the for...in loop, the first pass through the loop references the object's first property. The second pass through the loop references the object's second property and so on until all properties for that object have been referenced.
Example
In the following page, the custom function named dump_props writes out all properties for any object (obj) passed to it. It displays the name of the object as well via the passed obj_name argument:
<HTML>
<HEAD>
<SCRIPT Language = "JavaScript">
function dump_props(obj, obj_name) {
msgWindow=window.open("","displayWindow")
var result = ""
for (var i in obj) {
msgWindow.document.write (obj_name + "." + i + " = " + obj[i] + "<BR>") }
}
</SCRIPT>
</HEAD>
<BODY>
<FORM name = 'testform'>
<TEXTAREA NAME="SomeText" ROWS=3 COLS=25> type something here</TEXTAREA>
<INPUT type="button" value="Click Here" onClick = dump_props(document.testform.SomeText,'SomeText')">
</FORM>
</BODY>
</HTML>When executed, the BODY of this script displays a form with a textarea form field and a button. Clicking that buttons calls up the dump_props function to display all properties for the document.testform.SomeText object, writing the name SomeText with each pass through the loop. The result, which is shown in the following example, is a catalog of all properties associated with the form fields. The null properties typically are properties that are not associated with this particular type of form field:
SomeText.defaultChecked = null
SomeText.checked = null
SomeText.selectedIndex = null
SomeText.options = null
SomeText.length = null
SomeText.defaultValue = type something here
SomeText.value = (whatever the reader types into the box)
SomeText.form =
SomeText.name = SomeText
A function statement declares a user-defined JavaScript function, typically in the <HEAD> of a Web page.
Syntax
The syntax for the function statement is
function name([param] [, param] [..., param]) {
statements
}where name is the name that you assign to the function (cannot contain spaces, cannot be a reserved word) and the optional param statements are names that you assign to parameters that will be passed to the function with any call to the function. The params can be any combination of strings, numbers, and objects.
Description
The function() statement defines a custom JavaScript function that, once defined, can be called by any JavaScript code or event handler on the Web page. To ensure that a function is defined before it is called up, define all custom functions between the <HEAD>...</HEAD> tags of the Web page.
If you want the function to return a value, the function must include a return statement that specifies the value to return.
You cannot nest a function statement within another statement or within itself.
All parameters are passed to the function by value and any changes to the value are local to the function. In other words, if the function changes the value of the parameter, the change is not reflected globally or in the calling function. The only changed value that comes out of a function is the value specified in the return statement.
Example
The following Web page contains two custom functions named strToZero() and validate(). The strToZero takes any value, ensures that it is a number (not a string), and returns a number. If a non-numeric string value is passed to the function, the function returns the number 0.
The second function, validate(), does not return a value. Instead, it checks to see if the value passed to it is a number between 1 and 10. If the number is not between 1 and 10, the validate() function just displays the message: Please enter a number between 1 and 10.
Both functions are called by the onClick event handler of a form field. Note that the strToZero() function first ensures that the user's entry is indeed a number (not a string) and that the validate() function operates upon that number.
<HTML>
<HEAD>
<SCRIPT Language = "JavaScript">
//function convert any non-numeric value to a zero.
function strToZero(anyval) {
anyval = ""+anyval
if (anyval.substring(0,1) < "0" || anyval.substring(0,1) > "9") {
anyval = "0"
}
return eval(anyval)
}
//function to ensure that number is between 1 and 10.
function validate(anynum) {
if (anynum <1 || anynum > 10) {
alert ("Please enter a number between 1 and 10.")
}
}
</SCRIPT>
</HEAD>
<BODY>
<FORM>
Enter your rating:
<INPUT NAME = "Rating" SIZE = 2 onChange = "validate(strToZero(this.value))">
</FORM>
</BODY>
</HTML>
The if statement makes a decision within a script.
Syntax
The general syntax for the if statement is
if {condition) { statements1 }[else { statements2 }]
where condition is any expression that results in a true or false outcome and statements1 and statements2 are JavaScript code.
Description
When executed, the condition is evaluated and must return a true or false value. If the result is true, then the code within the first pair of curly braces ({}) (statements1) is executed. If the condition proves false, that code is ignored.
Else is optional. If included, the code within the second pair of curly braces (statements2) is executed if (and only if) the condition proves false.
You can nest if() statements, which means that either statements1 or statements2 can contain more if() statements.
When checking to see if a variable equals some value in an if() condition, be sure to use the double equal signs operator (==) rather than the single equal sign (=). To specify AND in an if()condition, use the && operator. To specify OR in an if() condition, use the || operator.
Example
In the following Web page, the genderOK() custom function converts the value passed to it to uppercase (using the toUppercase() method of the string object). The if() statement then checks to see if that string is letter M or the letter F. If it is, the function does not do anything. If the string is neither M or F, then the function displays the message: Please enter M or F in the Gender box.
<HTML>
<HEAD>
<SCRIPT Language = "JavaScript">
function genderOK(anystring) {
anystring = anystring.toUpperCase()
if (anystring == "M" || anystring == "F"){
//do nothing }
else {
alert ("Please enter M or F") }
}
</SCRIPT>
</HEAD>
<BODY>
<FORM>
Gender:<INPUT name='Gender' Size = 2 onChange = "genderOK(this.value)">
Name:<INPUT name='ReaderName' Size = 20>
</FORM>
</BODY>
</HEAD>
The new statement creates a new instance of an object type.
Syntax
The syntax for the new statement is
objectname = new objecttype (parameter1 [,parameter2] ...[,parameterN])
where objectname is the name you assign to the specific object being created, objecttype is the type of object you are creating, and parameters are properties of the object.
Description
Use the new keyword to create a new instance of an object in much the same way you would create a variable.
Example
In this example, you create a new date object named rightnow that reflects the system date and time when the page is opened. You then use the toLocaleString() method of the date object to display a message in the format Your visit begins at 05/15/90 19:30:00.
<HTML>
<BODY>
<SCRIPT language = "JavaScript">
rightnow = new Date()
document.write ("Your visit begins at ")
document.write (rightnow.toLocaleString())
</SCRIPT>
</BODY>
</HTML>
The return statement returns a value to a statement that called a custom function ans is used only within a custom function.
Syntax
The syntax for a return statement is
return value
where value is a value to return, or the name of a variable that contains the value to return.
Description
The return statement returns a value to whatever statement called it. If you want to base the return value on a decision, store the return value in a variable and return the variable at the end of the function.
Example
The following custom function sets a variable named retval to false. Then it loops through a large string (largestr) to see if one of its characters matches the character passed as onechar. If so, it changes the value of retval to true. When the function is finished, it returns the value of the retval variable to the calling statement.
<SCRIPT Language = "JavaScript">
function contains (onechar,largestr) {
retval = false
for (var i=0;i<=largestr.length-1;i++) {
if (largestr.charAt(i) == onechar) {
retval = true break
}
}
return retval
}
</SCRIPT>
The var statement is an optional statement used to create a new variable.
Syntax
The syntax for this statement is
var varname [= value] [..., varname [= value] ]
where varname is a variable name you create (it cannot contain spaces and cannot be a Reserved Word) and value is a value to store in the variable, or an expression that results in some value.
Description
In most cases, the var statement is optional. For example, these two statements are equivalent:var x = 10 x = 10
Both put the value 10 in a variable named x. If x does not already exist, it is created on the spot.
The scope of a variable is local to the function in which it is created. For example, if a custom function creates a variable y, that variable exists only while the function is being executed. When the function completes its task, the variable y ceases to exist.
To create a global variable (one that is accessible to multiple functions in a page) you must declare that variable outside of any function. Typically, you do so just under the <SCRIPT> tag in the head of a page before the first custom function is defined.
All variables are local to the current page. To extend a variable's scope to other pages, you need to copy the variable to a document cookie.
Example
This code snippet declares several global variables near the top of the first script in this page's <HEAD> section:
<HTML>
<HEAD>
<SCRIPT Language = "JavaScript">
//Global Variables
var RowsInForm = 5
var ProductsInList = 10
var SalesTaxRate = 0.0775
var TaxableState = "CA"
var ProdSubscript = 0
The while statement defines a loop that is executed until some condition proves false. It is usually used when no incrementing counter is needed.
Syntax
The syntax for the while statement is as follows:
while (condition) {
statements
}
where condition is an expression that evaluates to true or false and statements are any number of Javascript statements.
Description
A while loop is similar to a for loop except that there is no automatically incremented counter in the loop. The condition statement is evaluated once at the start of the loop, then each time execution passes through the loop. If condition proves true, code within the curly braces is executed. If condition proves false, code within the curly braces is ignored and execution resumes with the first statement after the closing curly brace (}).
Example
In the following code snippet, a while loop repeats a series of JavaScript statements until they come up with a random number that's between 1 and 10 (inclusive):
<SCRIPT Language = "JavaScript">
randomNumber = 0
while ((randomNumber < 1) || (randomNumber > 10)) {
now = new Date()
randomNumber = Math.abs(Math.sin(now.getTime()))
randomNumber = parseInt(randomNumber * 10.5) }
document.write ('random number = ',randomNumber)
</SCRIPT>
The with statement sets up a default object for a set of statements.
Syntax
The syntax for this statement is as follows:
with (object) {
statements
}
where object is the name of a specific object and statements are Javascript statements to be executed.
Description
Use with as an alternative to a series of lengthy object names or this. keywords.
Example
As an alternative to restating the Math. object name repeatedly in the statements, as shown here:
radius = 5.4
area = Math.PI * (radius*radius)
cosinePI = Math.cos(Math.PI/2)
sinePIdiv2 = Math.sin(Math.PI/2)You can just use with(Math) and enclose the statements in a pair of curly braces ({ }), as shown in the following example:
radius = 5.4
with (Math) {
area = PI * (radius*radius)
cosinePI = cos(PI/2)
sinePIdiv2 = sin(PI/2)
}

|
|
![]() |