Java Reference
In-Depth Information
The easiest way to work out what multiple conditions are doing is to split them up into smaller
pieces and then evaluate the combined result. In this example you have entered the value
30
,
which has been stored in the variable
myAge
. You'll substitute this value into the conditions to see how
they work.
Here's the first
if
statement:
if (myAge >= 0 && myAge <= 10) {
document.write("myAge is between 0 and 10<br />");
}
The first
if
statement is asking the question, “Is
myAge
between 0 and 10?” You'll take the LHS of
the condition first, substituting your particular value for
myAge
. The LHS asks, “Is 30 greater than or
equal to 0?” The answer is
true
. The question posed by the RHS condition is “Is 30 less than or equal
to 10?” The answer is
false
. These two halves of the condition are joined using
&&
, which indicates
the
AND
operator. Using the
AND
results table shown earlier, you can see that if LHS is
true
and RHS
is
false
, you have an overall result of
false
. So the end result of the condition for the
if
statement is
false
, and the code inside the braces won't execute.
Let's move on to the second
if
statement:
if ( !(myAge >= 0 && myAge <= 10) ) {
document.write("myAge is NOT between 0 and 10<br />");
}
The second
if
statement is posing the question, “Is
myAge
not between 0 and 10?” Its condition is
similar to that of the first
if
statement, but with one small difference: You have enclosed the condition
inside parentheses and put the
NOT
operator (
!
) in front.
The part of the condition inside the parentheses is evaluated and, as before, produces the same result—
false
. However, the
NOT
operator reverses the result and makes it
true
. Because the
if
statement's
condition is
true
, the code inside the braces
will
execute this time, causing a
document.write()
to
write a response to the page.
What about the third
if
statement?
if ( myAge >= 80 || myAge <= 10 ) {
document.write("myAge is 80 or above OR 10 or below<br />");
}
The third
if
statement asks, “Is
myAge
greater than or equal to 80, or less than or equal to 10?” Taking
the LHS condition first—“Is 30 greater than or equal to 80?”—the answer is
false
. The answer to the
RHS condition—“Is 30 less than or equal to 10?”—is again
false
. These two halves of the condition
are combined using
| |
, which indicates the
OR
operator. Looking at the
OR
result table earlier in this
section, you see that
false
OR
false
produces a result of
false
. So again the
if
statement's condition
evaluates to
false
, and the code within the curly braces does not execute.
The final
if
statement is a little more complex:
if ( (myAge >= 30 && myAge <= 39) || (myAge >= 80 && myAge <= 89) ) {
document.write("myAge is between 30 and 39 or myAge is between 80 and 89");
}