if (condition) {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, {}. Example. In the following example, the function checkData returns true if the number of characters in a Text object is three; otherwise, it displays an alert and returns false.
statements1
[ } else {
statements2 ]
}
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
}
}
for statement
A 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 ([initial-expression]; [condition]; [increment-expression]) {
When a for loop executes, the following occurs:
statements
}
<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>
while (condition) {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 only when the statements in the loop have been executed and the loop is about to be repeated. That is, the condition test is not continuous but is performed once at the beginning of the loop and again just following the last statement in statements, each time control passes through the loop. Example 1. The following while loop iterates as long as n is less than three:
statements
}
n = 0With each iteration, the loop increments n and adds that value to x. Therefore, x and n take on the following values:
x = 0
while( n < 3 ) {
n ++
x += n
}
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") }
breakExample. The following function has a break statement that terminates the while loop when i is three, and then returns the value 3 * x.
function testBreak(x) {
var i = 0
while (i < 6) {
if (i == 3)
break
i++
}
return i*x
}
continueIn contrast to the break statement, continue does not terminate the execution of the loop entirely. Instead,
i = 0
n = 0
while (i < 5) {
i++
if (i == 3)
continue
n += i
}
objectName = new objectType ( param1 [,param2] ...[,paramN] )The following example creates an Array object with 25 elements, then assigns values to the first three elements:
musicTypes = new Array(25)The following examples create several Date objects:
musicTypes[0] = "R&B"
musicTypes[1] = "Blues"
musicTypes[2] = "Jazz"
today = new Date()The following example creates a user-define object type car, with properties for make, model, and year. The example then creates an object called mycar and assigns values to its properties. The value of mycar.make is the string "Eagle", mycar.year is the integer 1993, and so on.
birthday = new Date("December 17, 1995 03:24:00")
birthday = new Date(95,12,17)
function car(make, model, year) {For more information on new, see "new".
this.make = make
this.model = model
this.year = year
}
mycar = new car("Eagle", "Talon TSi", 1993)
this keyword
Use the this keyword to refer to the current object. In general, this refers to the calling object in a method. Use this as follows:
this[.propertyName]
Example 1. Suppose a function called validate validates an object's value property, given the object and the high and low values:
function validate(obj, lowval, hival) {
You could call validate in each form element's onChange event handler, using this to pass it the form element, as in the following example:
if ((obj.value < lowval) || (obj.value > hival))
alert("Invalid Value!")
}<B>Enter a number between 18 and 99:</B>
Example 2. When combined with the form property, this can refer to the current object's parent form. In the following example, the form myForm contains a Text object and a button. When the user clicks the button, the value of the Text object is set to the form's name. The button's onClick event handler uses
<INPUT TYPE = "text" NAME = "age" SIZE = 3
onChange="validate(this, 18, 99)">this.form
to refer to the parent form, myForm.
<FORM NAME="myForm">
Form name:<INPUT TYPE="text" NAME="text1" VALUE="Beluga">
<P>
<INPUT NAME="button1" TYPE="button" VALUE="Show Form Name"
onClick="this.form.text1.value=this.form.name">
</FORM> for...in statement
The 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) {
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.
statements }function dump_props(obj, obj_name) {
For an object car with properties make and model, result would be:
car.make = Ford
var result = ""
for (var i in obj) {
result += obj_name + "." + i + " = " + obj[i] + "<BR>"
}
result += "<HR>"
return result
}
car.model = Mustang
with statement
The with statement establishes 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. A with statement looks as follows:
with (object){
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.
statements
}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. */