Conditionals

Conditional statements let you specify the conditions that must be met before an action can take place. The conditions themselves are normally logical expressions that evaluate to a Boolean value. Before we delve any deeper into conditionals, we should take a closer look at Boolean data and operations.

`

Boolean Comparisons

Boolean expressions, which can have only one of two values (true or false), are especially helpful when used with conditional statements. You can assign a Boolean value to a variable as follows:

 myVar=true 

As you saw in Chapter 8, you can use mathematical operators for mathematical expressions; for instance, you can use the addition operator to write the expression 4+4, which evaluates to 8. In the same way, you can use logical operators for Boolean expressions; for example, the expression 4==4 evaluates to true.

Notice the two equal signs in the Boolean equality expression. A single equal sign is an assignment operator; it assigns one value to another. The equality operator is composed of two equal signs; it tests the values on each side and results in a Boolean value of true if the values are equal and a value of false if they are not. Thus, the expression 4==5 evaluates to false, whereas 4==4 evaluates to true. Another frequently encountered logical operator is the inequality operator, !=, which tests whether two values are not equal. For example, the expression 4!=5 evaluates to true because it is true that 4 does not equal 5. These types of tests are known as Boolean, logical, or conditional operations. Table 9-1 describes a number of the most common logical operators.

Table 9-1 Common Logical Operators

Operator Test Performed
== Equality. Tests whether one value is equal to another. For example, if x is equal to the number 4, these three statements all evaluate to true: x==4, x=="4", and false==false. In the second expression, the string 4 is automatically converted to a number when it is compared. (See Chapter 8 for more information about data conversion.)
!= Inequality. Tests whether two values are not equal. For example, the statement 4!=5 evaluates to true, and 4!=4 is false.
< Less than. Tests whether a value is less than another value. For example, if x is equal to 4, the expression x<5 is true, the expression x<4 is false (because 4 is not less than 4), and the expression x<3 is false.
> Greater than. Tests whether a value is greater than another value. For example, if x is equal to 4, the expression x>5 is false and the expression x>3 is true.
<= Less than or equal to. Tests whether a value is less than or equal to another value. For example, if x is equal to 4, the expression x<=5 is true, the expression x<=4 is true, and the expression x<=3 is false.
>= Greater than or equal to. Tests whether a value is greater than or equal to another value. For example, if x is equal to 4, the expression x>=5 is false, the expression x>=4 is true, and the expression x>=3 is true.
! NOT. Reverses the value of a Boolean expression. For example, if x is equal to true, the expression !x evaluates to false and the expression !(4==5) evaluates to true.
&& AND. Compares two Boolean expressions, and if both expressions are true the operation returns true; if either is false, it returns false. For example, the expression (4==4)&&(4<5) evaluates to true. If the variable hungry is true and the variable haveFood is false, and if canEat equals hungry&&haveFood, then canEat evaluates to false.
|| OR. Compares two Boolean expressions, and if either expression is true the operation returns true; only if both are false does it return false. For example, if x equals 4 and y equals 5, the expression (x==4)||(y==4) equals true and the expression (x= =3)||(y= =4) equals false.
=== Identity. Tests whether two values are not only equal but also of the same type. For example, the expression 4===4 evaluates to true, whereas the expression 4==="4" evaluates to false. (The second expression returns false because no type conversions occur in an identity operation.)
!== Nonidentity. Tests whether two values are unequal or of different data types, or unequal and of different data types. This operation returns true unless both values are of the same type and have the same value. For example, the expression 4!==4 evaluates to false, while the expressions 4!==5, (4!=="5"), and 4!=="4" all evaluate to true. (No type conversions occur in a nonidentity operation.)

if... Statements

Now that you've seen how to use Boolean comparisons, let's put them to work in some conditional statements. The most basic type of conditional statement is the if... statement, commonly known in many languages as an if...then statement. This statement specifies that if a condition is met (if a value is true), then an action should occur. If the value is not true, the action does not take place. An if... statement begins with the term if followed first by a Boolean expression in parentheses and then by a set of actions enclosed in curly braces. The following line of code demonstrates a basic if... statement:

 if(x==4){alert("x is equal to four")} 

This statement first tests to see whether x is equal to 4. If it is, the code produces an Alert dialog box containing the text x is equal to four.

An expanded version of the if... statement is the if...else statement. This statement specifies that if a condition is met, then an action should occur; otherwise (else), a different action should occur. Code Listing 9-3 expands on Code Listing 9-2 and shows how an if...else statement can be used to check data for errors. Figure 9-3 shows what happens if you enter a letter instead of a number in the text area.

Code Listing 9-3.

 <HTML> <HEAD> <TITLE>Listing 9-3</TITLE> <SCRIPT LANGUAGE="JavaScript"> function rndNum(maxNum){   num=Math.random()   num=num*maxNum   num=Math.ceil(num)   return num } function tellUser(specifiedNum){   if (isNaN(specifiedNum)){     alert("Please enter only numbers.")   }   else {     alert(rndNum(specifiedNum))   } } </SCRIPT> </HEAD> <BODY> Type a number in the area below, and then click Calculate.<BR> The page will generate a random number between 1 and the  number you entered.<BR> <FORM> <TEXTAREA NAME="TextNum">10</TEXTAREA> <BR> <INPUT TYPE="button" VALUE="Calculate"         onclick="tellUser(TextNum.value)"> </FORM> </BODY> </HTML> 

click to view at full size.

Figure 9-3. Checking data for errors.

The tellUser function first uses the isNaN method to test the value that is passed to it. (This method returns true if the value is not a number and false if the value is a number.) If the value is not a number, the tellUser function advises the user to enter only numbers. Otherwise, if the value passed is a number, tellUser calls the rndNum function and operates the same as Code Listing 9-2.

The Conditional Operator

The conditional operator allows what is essentially a compressed if...else statement. The following line of code shows the conditional operator in use:

 alert(x>4?"x is greater than 4":"x is not greater than 4") 

A conditional statement begins with a Boolean test, followed by a question mark. It then indicates the value that should result if the test is true, separated by a colon from the value that should result if the test is false. In the alert example shown here, the conditional statement is the code inside the parentheses. This statement will return x is greater than 4 or x is not greater than 4 depending on whether the test x>4 is true or false. We could have written this code as an if...else statement as follows:

 if (x>4){alert("x is greater than 4")} else{alert("x is not greater than 4")} 

switch Statements

A switch statement is like an expanded if...else statement. It lets you specify different actions for different values of an expression. (In some other languages, a switch statement is called a case statement.) Code Listing 9-4 uses a switch statement; see Figure 9-4 for an example of the page that results.

Code Listing 9-4.

 <HTML> <HEAD> <TITLE>Listing 9-4</TITLE> <SCRIPT LANGUAGE="JavaScript"> function testColor(givenColor){   givenColor=givenColor.toLowerCase()   switch (givenColor){     case "blue" : alert("That is my favorite color!") ; break     case "green": alert("Yuck, I don't like green.") ; break     case "red"  : {       alert("I don't like red as much as blue.")       break     }     default:alert("I like blue the best.") ; break   } } </SCRIPT> </HEAD> <BODY> What is your favorite color?<BR> <FORM>   <TEXTAREA NAME="TextArea1">Blue</TEXTAREA><BR>   <INPUT TYPE="button" VALUE="Test" onclick="testColor(TextArea1.value)"> </FORM> </BODY> </HTML> 

click to view at full size.

Figure 9-4. Using a switch statement.

You can think of a switch statement as a list of different sets of actions that should be taken in different circumstances. The switch statement begins with the word switch followed by the expression being tested, surrounded by parentheses. After this, curly braces define the beginning and end of the list of actions to take in different cases. These actions take the form of the word case followed by a potential value of the expression, a colon, and then the desired action. You can also specify an optional default action that will take place when the value does not match any of the previously specified cases.

In Code Listing 9-4, when the user types the name of a color into the text area and clicks the Test button, the testColor function is called. This function converts the text in the text area to lowercase, which allows us to compare it to a set of values. (Without this conversion, it is more difficult to test the value entered by the user; the string blue is not equivalent to Blue, for instance.) The switch statement then begins. It tests the givenColor variable and specifies the action to be taken if the value of the variable is equal to blue, red, or green as well as a default action if the value is anything else. Each case can have multiple actions, each written on separate lines or separated with semicolons. The final action of each case should be a break statement, which marks the end of that case and prevents the actions specified for other cases in the switch statement from executing. Support for the switch statement is relatively recent; it is not supported in version 3 of Navigator or Internet Explorer. (Technically, it is not version 3 of Internet Explorer that does not support the switch statement. Instead it is the version of the JScript engine that shipped with it. New versions of the JScript engine can be downloaded from http://msdn.microsoft.com/scripting and used in versions 3 and later of Internet Explorer.)



Dynamic HTML in Action
Dynamic HTML in Action
ISBN: 0735605637
EAN: 2147483647
Year: 1999
Pages: 128

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