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> <h3> 1 <script type="text/javascript"> <!-- Hiding JavaScript from old browsers 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. "); } //--> 8 </script> </h3> </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).
3,4 If the value of the variable age is greater than or equal to 55, line 4 is executed (see Figure 6.2).
5 This closing curly brace closes the block of statements following the if expression. When 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.
Figure 6.1 The user is prompted for input.
Figure 6.2 If the age entered was greater than 55, this message is displayed.
The Conditional Operator
The conditional operator, called a ternary operator, was discussed in Chapter 5, "Operators." Because it is often used as a shortcut for the if/else conditional statement, it is reviewed again here.
Format
conditional expression ? expression : expression
Example
x ? y : z If x evaluates to true, the value of the expression becomes y, else the value of the expression becomes z big = (x > y) ? x : y If x is greater than y, x is assigned to variable big, else y is assigned to variable big
An if/else statement instead of the conditional statement:
if (x > y) { big = x; } else{ big = y; }
Example 6.2.
<html> <head> <title>Conditional Operator</title> </head> <body bgcolor="lightblue"> <big> <script type ="text/javascript"> 1 var age = prompt("How old are you? ", ""); 2 var price = (age > 55 ) ? 0 : 7.50; 3 alert("You pay $" + price + 0); </script> </big> </body> </html>
Explanation
- The user is prompted for input. The value he or she enters in the prompt box is assigned to the variable age.
- If the value of age is greater than 55, the value to the right of the ? is assigned to the variable price; if not, the value after the : is assigned to the variable price.
- The alert dialog box displays the value of the variable price.
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) { statement(s); } else if (condition) { statement(s); } else if (condition) { statement(s); } else{ statement(s); }
If the first conditional expression following the if keyword is true, the statement or block of statements following the expression is 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 ifs 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.3.
<html> <head> <title>Conditional Flow Control</title> </head> <body> <h2> 1 <script type="text/javascript"> <!-- 2 var age=eval( prompt("How old are you? ","")); 3 if( age > 0 && age <= 12 ){ 4 alert("You pay the child's fare. "); } 5 else if( age > 12 && age < 60 ){ 6 alert("You pay the regular adult fare. "); } else { 7 alert("You pay the senior fare! "); } //--> 8 </script> </h3> </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 0 and age is also less than or equal to 12, then line 4 is executed and the program continues at line 8. |
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 and control goes to line 8. You can have as many else ifs 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.
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.4.
<html> <head> <title>The Switch Statement</title> </head> <body> <script type="text/javascript"> <!-- 1 var day_of_week=Math.floor((Math.random()* 7)+1); // Get a random number between 1 and 7 // Monday is 1, Tuesday is 2, etc. 2 switch(day_of_week){ 3 case 1: case 2: case 3: case 4: 4 alert("Business hours Monday through Thursday are from 9am to 10pm"); 5 break; case 5: alert("Business hours on Friday are from 9am to 6pm"); break; case 6: alert("Business hours on Saturday are from 11am to 3pm"); break; 6 default: alert("We are closed on Sundays and holidays"); 7 break; 8 } //--> </script> </body> </html>
Explanation
- The random number function generates a random number between 1 and 7 inclusive when the script is executed. The random number is stored in a variable called day_of_week.
- The day_of_week value of the switch expression is matched against the values of each of the case labels below.
- The first case that is tested is 1. If the random number is 1, the message "Business hours Monday through Thursday are from 9am to 10pm" will be displayed in the alert dialog box. The same is true for case 2, 3, and 4.
- This statement is executed if case 1, 2, 3, or 4 are matched. Note there are no break statements associated with any of these 4 case statements. Program control just drops from one case to the next, and if cases 1, 2, 3, or 4 are not matched, execution control goes to the next case (case 5) for testing.
- The break statement causes program control to continue after line 8. 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. The break statement sends control of the program to line 8.
- The default statements are executed if none of the cases are matched.
- 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.
- The final curly brace ends the switch statement. Figure 6.3 displays examples of the output.
Figure 6.3 A random number between 1 and 7 determines which is matched and executed.