
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
132
|
Chapter 5: Operators
Nice, huh? Sometimes programming is so elegant. Such distinctive vertical lines...
such supple parentheses...
Logical Expressions and Data Values
Using logical operators to calculate a Boolean result is analogous to using arithmetic
operators to calculate a numeric result. For example, the following four operands
and three operators are used to calculate a single result:
(userStatus = = "registered") || (userStatus = = "specialGuest")
If the user is not registered, but is a special guest, this expression reduces to:
false || true
which in turn reduces to the Boolean result true.
Here is an analogous arithmetic operation that reduces to a single number:
(1 + 2) * (3 + 4) // Four values (1, 2, 3, 4), which become...
3 * 7 // two values (3, 7), which become...
21 // a single value (21)
Remember, a complex expression that reduces to a Boolean can be used anywhere
a single Boolean value is required (such as the test expression of a conditional
statement).
Logical OR
The logical OR operator is most commonly used to initiate some action when at least
one of two conditions is met. For example, “If I am hungry or I am thirsty, I’ll go to
the kitchen.” The symbol for logical OR is made using two vertical line characters
(
||). Typically, the | character is accessible using