Using Conditional Statementsif...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 Statementswitch (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 Statementsfor StatementA 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 StatementExecutes 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 StatementThe do
|
while StatementA while (condition) { statements } |
break StatementThe 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 StatementThe 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) |