8.6.2 Selection
Selection statements give imperative languages the ability to make choices based on the results of certain condition tests. These condition tests take the form of Boolean expressions, which are expressions that evaluate to either true or false.[5] There are various types of Boolean expressions, but the types supported in Watson JavaScript are based on relational operators. Relational operators compare two expressions of like type to determine whether their values satisfy some criterion. The general form of all Boolean expressions supported in Watson JavaScript is:
expression relational_operator expression
Watson JavaScript includes six relational operators for comparing numeric-valued expressions. They are:
> meaning “greater than”
< meaning “less than”
>= meaning “greater than or equal to”
<= meaning “less than or equal to”
== meaning “equal to”
!= meaning “not equal to”
So, for example, when x is 15 and y is 25 the expression x > y evaluates to false, since 15 is not greater than 25.
It is vitally important that you not confuse the relational operator “==” with the assignment operator “=” – though they look similar, they do very different things. Assignment places a value into a variable, thus “x = 15;” assigns the value 15 to the variable x, regardless of the value originally stored in x. On the other hand, “x == 15” compares the current value stored in variable x to the number 15. If these two values are equal the expression returns true, otherwise it returns false.
Here are some additional examples of Boolean expressions that use the numeric-based relational operators. These examples assume that the variable x holds 15 and y holds 25.
Notice that the last expression always evaluates to false, regardless of the value of x. This is because there is no possible value for x that will be equal to that value plus one. Another point illustrated by these examples is that relational operators have a lower precedence than mathematical operators. During expression evaluation, all multiplication, division, addition, and subtraction operations are performed before any relational operations.
In addition to the six relational operators for mathematical expressions, there are four relational operators defined on string expressions. These operators are:
The relational expression:
favoriteShow == “X-Files”;
will be true if favoriteShow is a text variable that currently contains the sequence of characters “X-files”. If the variable contains any other sequence of characters, the expression will be false. It is important to note that text string comparisons are “case sensitive”. This means that upper and lower case letters are considered to be separate characters for comparison purposes. If favoriteShow contains the string “x-files” with a lower case “x”, the above expression would evaluate to false.
In general, comparisons are based on lexicographic, or dictionary, order. So, x > y when x is “Fox” and y is “Dana” evaluates to true, since “Fox” follows “Dana” using dictionary order. However, if x were assigned the value “Cancer Man”, then the same expression would evaluate to false since the “C” in “Cancer Man” would not follow the “D” in “Dana”. You should always keep in mind that string comparison operators are case sensitive – the rule being that upper case letters precede lower case letters. Thus, the expression
“Fox” < “alien life form”
evaluates to true, since capital “F” precedes lower case “a”.
Here are some additional examples of Boolean expressions that use the string-based relational operators. These examples assume that the variable A holds “UFO” and B holds “FBI”.
Selection statements use the results of Boolean expressions to choose which sequence of actions to perform next. Watson JavaScript supports two different selection statements: If-Else and If. Each is described below.
Figure 8.11: An illustration of the behavior of the If-Else selection construct
An If-Else statement allows a program to make a two-way choice based on the result of a Boolean expression. The general form of If-Else statements is:
If-Else statements specify a Boolean expression and two separate blocks of code: one that is to be executed if the expression is true, the other to be executed if the expression is false. The behavior of the If-Else statement is illustrated graphically in Figure 8.11
Figure 8.12: A program that illustrates selection via If-Else
Figure 8.12 presents a program that uses an If-Else statement to determine whether a person is of legal drinking age (in the US). The program prompts a user to enter his or her age and then stores whatever the user inputs into a variable called age. This variable is then tested against the constant 21. If age is less than 21, the text string “No beer for you.” is displayed. Otherwise, if age is greater than or equal to 21, the text string “Here, have a cold one!” is displayed.
If-Else statements always choose one code block or the other based on the value of the Boolean expression. If the condition is true, the first code block, sometimes called the “then” block, is executed and the second code block is skipped. If the condition is false, the first code block is skipped and the second code block, sometimes called the “else” block, is executed. Under no circumstances will both statements blocks be executed.
While only one statement occurs in the “then” and “else” blocks of the program of Figure 8.12, If-Else structures in general allow multiple statements per block. The program of Figure 8.13 illustrates multi-statement “then” and “else” blocks. The purpose of the program is to compute the absolute value of an input number. The program begins by requesting input from the user and storing that input in the variable num. The phrase “The absolute value of the ” is then displayed on the screen. Next, num is tested to determine whether its value is less than zero. If it is, the sequence of “write” statements in the “then” block generates a message of the form:
negative number, <num>, is <abs>
where <num> is replaced with the value of the input number and <abs> is replaced with a positive version of the input number. Otherwise, the “else” block generates a message of the form:
non-negative number, <num>, is <num>
where both occurrences of <num> are replaced with the value of the input number.
Figure 8.13: A program that illustrates multi-statement “then” and “else” blocks
Finally, following the If-Else construct, a “writeln” statement prints a period. Note that since this statement occurs after the end of the If-Else block, the period will always be printed, regardless of whether the “then” block or the “else” block was executed.
The fact that If-Else statements allow other statements to be embedded within them raises an interesting question: “Can an If-Else statement occur within the “then” or “else” block of another If-Else statement?” The answer to this question is “sure”. In fact, these “nested” If-Else structures are common in all but the simplest programs.
The idea of nested If-Else statements is illustrated in Figure 8.14. This program determines whether or not a person is classified as a “baller” based on their age and income. For the purposes of this example, a baller is defined as someone under 25 years of age with an income of $50,000 or more per year. Because this definition depends on two condition tests, age and income, an If-Else statement for testing one of them must be embedded in an If-Else statement to test the other.
Figure 8.14: A program that illustrates nested If-Else statements
The program begins by gathering the age and income of the user. The value of age is tested to determine if the user is less than 25 years old. If so, the “then” statement block is executed. This block consists of a single If-Else statement that determines whether income is $50K or more. If so, the message “You’re a baller.” is displayed, since the user is both under 25 and makes $50K or more per year. If the condition involving income is false, the message “You’re too poor to be a baller.” is displayed. This makes sense, because the user is young enough (under 25) to be a baller, but he or she lacks the necessary “bling”.
Returning to the outer If-Else, if the user is 25 or older, he or she cannot be a baller.[6] Rather than just telling the user that he or she is too old, the program goes ahead and tests the income level anyway. If the user makes $50K or more per year, then he or she would be a baller if only they were younger. Hence the message displayed in this case is “You’re too old to be a baller.” However, if the income level is below $50K then the user is both too old and too poor. These deficiencies are pointed out in the final message.
Note that following the “}” of the outer If-Else a “writeln” statement occurs. This statement will print “Later…” regardless of which of the four “baller diagnostic messages” were reported.You should now have a pretty good idea how the If-Else statement works. Before leaving the topic of selection, however, we should talk about the other selection statement supported by JavaScript – the “If” statement.
The If statement is similar to If-Else statement except it does not include an “else” block. The general form of the If statement is:
As you probably suspect, if the Boolean expression is true, the statements in the code block enclosed in braces are executed. Otherwise, they are skipped. Program control returns to a single path at the end of the block, so the statement following the “}” will always be executed regardless of the results of the Boolean Expression. The behavior of the If construct is graphically illustrated in Figure 8.15.
Figure 8.15: An illustration of the behavior of the If selection construct
Figure 8.16: A program that illustrates selection via If
If statements are generally used by programmers to allow their programs to detect and handle conditions that require “special” or “additional” processing. This is in contrast to If-Else statements, which can be viewed as selecting between two “equal” choices.
The program of Figure 8.16 illustrates the use of an If statement. The purpose of the program is to report whether a user is or is not a minor based on his or her age. The program begins by prompting the user to enter his or her age. The input is then stored in the variable age. Next, the text string “You are ” is displayed. An If statement then checks to see whether age is greater than or equal to 18. If the condition is true, the word “not ” is printed. Finally, the phrase “a minor.” is displayed. Thus, this program prints either: “You are not a minor.” or “You are a minor.” depending on the value of age.
Exercises for Section 8.6.2
(a) 15 (b) 10 (c) 5
(a) Given a value of 15 for "a" and 10 for "b".
(b) Given a value of 10 for "a" and 15 for "b".
Footnotes
[5] Boolean expressions are named for the mathematician George Boole. Hence, the word “Boolean” should always be capitalized.
[6] Note: Our definition is equal opportunity – both men and women can be ballers.