Control of Program Flow

Using Conditional Statements

if...else Statement

if (condition) {
   statements1 
}

or

if (condition) {
   statements1 
}
else {
   statements2 
}

"{" ,"}" can be omitted, if only one staement is in the block.

Example 1:

yn=confirm("Are you sure to quit?");
if (yn)
   self.close();
else 
   alert("Welcome to Continue!");

Example 2:

if (var1 == 1) {
   function1(var1);
}
else if (var1 == 2) {
   function2(var1);
}
switch Statement
switch (expression){
   case label : 
      statements;
      break;
   case label : 
      statements;
      break;
   ...
   default : statements;
}

Example:

switch (fruit) {
   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 " + fruit + ".<BR>"); 
} 

Loop Statements

for Statement

A for loop repeats until a specified condition evaluates to false.

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

Example:

sum=0;
for (var i=1; i<=100;i++) {
   sum += i;
}

sum1=0;
for (i=1,j=10;i<11;i++,j--) {
sum1 =sum1 + i*j;
}

for ... in Statement

Executes statements for each element of an object or array.

for (variable in ObjectOrArrayName) {
    statements
} 

Example 1:

for (i in window) {
    document.write("window.",i,"=", window[i],"<br>");
}

Example 2:

var arr=new Array(10);
for (i=0;i<10;i++) {
   arr[i]=i*i;
}
for (var1 in arr) {
   document.write("arr[",var1,"] = ", arr[var1],"<br>");
}

do...while Statement

The do...while statement repeats until a specified condition evaluates to false.

do {
   statements
} while (condition)


Example:
y=1;
x=2;
do {
   x *= 2;
} while (x<y);
// Now x is 4. 

while Statement

A while statement executes its statements as long as a specified condition evaluates to true.

while (condition) {
   statements
}
Example:
y=1;
x=2;
while (x<y) {
   x *= 2;
} 
// x is not changed.

break Statement

The break statement can be used in a while, for, and labeled statement.

var1=5;
sum=0;
for (i=1;i<=10;i++) {
   if (i==var1) break;
   sum += i;
}
// Now sum is 10 (= 1+2+3+4)

continue Statement

The continue statement can be used in a while, for, and labeled statement.
In a while or for statement, continue terminates the current loop and continues execution of the loop with the next iteration.

var1=5;
sum=0;
for (i=1;i<=10;i++) {
   if (i == var1) continue;
   sum += i;
}
// Now sum is 50 (= 1+2+3+4+6+7+8+9+10)