6.2 Conditionals


Conditional constructs control the flow of a program. If a condition is true, the program will execute a block of statements and if the condition is false, flow will go to an alternate block of statements. Decision-making constructs ( if, else, switch ) contain a control expression that determines whether a block of expressions will be executed. If the condition after the if is met, the result is true, and the following block of statements is executed; otherwise the result is false and the block is not executed.

FORMAT

 
 if (condition){     statements; } 

Example:

 
 if ( age > 21 ){     alert("Let's Party!"); } 

The block of statements (or single statement) is enclosed in curly braces. Normally, statements are executed sequentially. If there is only one statement after the conditional expression, the curly braces are optional.

6.2.1 if/else

"You better pay attention now, or else . . . " Ever heard that kind of statement before? JavaScript statements can be handled the same way with the if/else branching construct. This construct allows for a two-way decision. The if evaluates the expression in parentheses, and if the expression evaluates to true, the block after the opening curly braces is executed; otherwise the block after the else is executed.

FORMAT

 
 if (condition){     statements1; } else{     statements2; } 

Example:

 
 if ( x > y ){     alert( "x is larger"); } else{     alert( "y is larger"); } 
Example 6.1
 <html>     <head>     <title>Conditional Flow Control</title>     </head>     <body> 1   <script language=javascript>         <!--  Hiding JavaScript from old browsers         document.write("<h3>"); 2       var age=prompt("How old are you? ",""); 3  if( age >= 55 ){  4  document.write("You pay the senior fare! ");  5  }  6  else{  7  document.write("You pay the regular adult fare. ");   }  document.write("</h3>");         //--> 8   </script>     </body>     </html> 

EXPLANATION

1 JavaScript program starts here.

2 The prompt dialog box will display the message " How old are you? ". Whatever the user types into the box will be stored in the variable age . (See Figure 6.1.)

Figure 6.1. The user is prompted for input.

graphics/06fig01.jpg

3, 4 If the value of the variable age is greater than or equal to 55 , line 4 is executed. (See Figure 6.2.)

Figure 6.2. If the age was entered was greater than 55, this message is displayed.

graphics/06fig02.jpg

5 This closing curly brace closes the block of statements following the if expression. Because there is only one statement in the block, the curly braces are not required.

6, 7 The else statement, line number 7, is executed if the expression in line 3 is false.

8 This tag marks the end of the JavaScript program.

6.2.2 if/else if

"If you've got $1, we can go to the Dollar Store; else if you've got $10, we could get a couple of movies; else if you've got $20 we could buy a CD . . . else forget it!" JavaScript provides yet another form of branching, the if/else if construct. This construct provides a multiway decision structure.

FORMAT

 
 if (condition) {     statements1; } else if (condition)  {     statements2; } else if (condition)  {     statements3; } else{     statements4; } 

If the first conditional expression following the if keyword is true, the statement or block of statements following the expression are executed and control starts after the final else block. Otherwise, if the conditional expression following the if keyword is false, control branches to the first else if and the expression following it is evaluated. If that expression is true, the statement or block of statements following it are executed, and if false, the next else if is tested . All else if s are tested and if none of their expressions are true, control goes to the else statement. Although the else is not required, it normally serves as a default action if all previous conditions were false.

Example 6.2
 <html>     <head>     <title>Conditional Flow Control</title>     </head>     <body> 1   <script language=javascript>     <!--     document.write("<H2>"); 2   var age=eval( prompt("How old are you? ","")); 3  if( age > 0 && age <= 12 ){  4       document.write("You pay the child's fare. ");     } 5  else if( age > 12 && age < 60 ){  6       document.write("You pay the regular adult fare. ");     } 7  else {  document.write("You pay the senior fare! ");     }         document.write("</H2>");     //--> 8   </script></body></html> 

EXPLANATION

1 JavaScript program starts here.

2 The prompt dialog box will display the message " How old are you? ". Whatever the user types into the box will be converted to a number by the eval() method and then stored in the variable age .

3, 4 If the value of the variable age is greater than and age is also less than or equal to 12 , then line 4 is executed.

5, 6 If the expression on line 3 is false, the JavaScript interpreter will test this line, and if the age is greater than 12 and also less than 60, the block of statements that follow will be executed. You can have as many else if s as you like.

7 The else statement, line number 7, is executed if all of the previous expressions test false. This statement is called the default and is not required.

8 This tag marks the end of the JavaScript program.

6.2.3 switch

The switch statement is an alternative to if/else if conditional construct (commonly called a "case statement") and may make the program more readable when handling multiple options. It is supported in both Netscape Navigator and Internet Explorer. [1]

[1] Added to JavaScript 1.2 and supported by Internet Explorer 4.0+ and Netscape 4+.

FORMAT

 
 switch (expression){ case label :     statement(s);     break; case label :     statement(s);     break;     ... default : statement; } 

Example:

 
 switch (color){ case "red":     alert("Hot!");     break; case "blue":     alert("Cold.");     break; default:     alert("Not a good choice.");     break; } 

The value of the switch expression is matched against the expressions, called labels, following the case keyword. The case labels are constants, either string or numeric. Each label is terminated with a colon . The default label is optional, but its action is taken if none of the other cases match the switch expression. After a match is found, the statements after the matched label are executed for that case. If none of the cases are matched, the control drops to the default case. The default is optional. If a break statement is omitted, all statements below the matched label are executed until either a break is reached or the entire switch block exits.

Example 6.3
 <html>     <head>     <title>The Switch Statement</title>     </head>     <body>  <script language=javascript>  <!-- 1   var color=prompt("What is your color?",""); 2  switch(color){  3  case "red":  document.bgColor="color";             document.write("Red is hot."); 4  break;  5  case "yellow":  document.bgColor=color;             document.write("Yellow is warm."); 6  break;  7  case "green":  document.bgColor="lightgreen";             document.write("Green is soothing."); 8  break;  9  case "blue":  document.bgColor="#RRGGBB";             document.write("Blue is cool."); 10  break;  11  default:  document.bgColor="white";             document.write("Not available today. We'll use white"); 12          break; 13      }         //-->     </script>     </body>     </html> 

EXPLANATION

  1. The prompt dialog box will ask the user to type a color. After the user presses the OK button, the switch statement is entered. (See Figure 6.3.)

    Figure 6.3. The user enters a color value.

    graphics/06fig03.jpg

  2. The color value of the switch expression is matched against the values of each of the case labels below.

  3. The first case that is tested is "red" . If the user typed red as his choice, then the background color of the document's window will turn red and the message " Red is hot. " will be displayed in the document.

  4. The break statement causes program control to continue after line 13. Without it, the program would continue executing statements into the next case, "yellow" , and continue doing so until a break is reached or the switch ends ”and we don't want that.

  5. The first case that is tested is "red" . If the user typed yellow as his choice, then the JavaScript interpreter will skip the "red" case and test the next one which is "yellow" . Since that value is matched successfully against the value of the color variable, the background color of the document's window will turn yellow and the message " Yellow is warm. " will be displayed in the document.

  6. The break statement sends control of the program to line 13.

  7. If "red" and "yellow" are not matched successfully against the value of the color variable, then "green" is tested, and if there is a match, then its block of statements is executed. (See Figure 6.4.)

    Figure 6.4. Output from Example 6.3. The "green" case was matched successfully.

    graphics/06fig04.jpg

  8. The break statement sends control of the program to line 13.

  9. If "red", "yellow" , or "green" are not matched successfully against the value of the color variable, then "blue" is tested, and if there is a match, then its block of statements are executed. (The color is assigned the RGB hexidecimal value.)

  10. The break statement sends control of the program to line 13.

  11. The default statement block is executed if none of the above cases are matched.

  12. This final break statement is not necessary, but is good practice in case you should decide to replace the default with an additional case label.

  13. The final curly brace ends the switch statement.



JavaScript by Example
JavaScript by Example (2nd Edition)
ISBN: 0137054890
EAN: 2147483647
Year: 2003
Pages: 150
Authors: Ellie Quigley

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net