Control Structures
Control Structures provide the means for making decisions about what to do, based on some condition, or for automating a series of repetitive operations by looping back to the beginning of the operation while some condition is true or until some condition is met.
There are three general kinds of control structures in JavaScript:
If [... else] Structures
The if control structure evaluates some condition, and then performs a series of operations if the condition is true. There is an optional else clause that causes some other set of operations to be performed if the control condition is false. The basic syntax for the control structure is:
if (condition statement) {
code to be executed if condition is true
}
[else {
code to be executed if condition is false
}]
Example
if ((browser == "Netscape") && (ver1 >= 4)){
itsNetscape()
}
else{
itsMsie()
}
While Structures
The while control structure loops through a series of commands while a condition remains true. The basic syntax for the while structure is as follows:
while (condition statement) {
code to be executed
}
Example
var x = 1
var myArray = new Array(10)
// populate the array with the integers 1-10
while ( x <= 10 ) {
myArray[(x-1)] = x;
x++;
}
For Structures
The for structure offers a more sophisticated looping structure than the while structure by allowing you to specify the initial condition and update of the condition in addition to the condition to be met for continuing the loop. The basic syntax of the for structure is as follows:
for (initial condition; condition statement; update statement) {
code to be executed
}
Example
var myArray = new Array(10)
// populate the array with the integers 1-10
for ( x = 1; x<= 10; x++ ) {
myArray[(x-1)] = x;
}
|