Java Reference
In-Depth Information
Any code within the braces will be executed only if the condition
degCent < 100
is
false
.
The following table details the possible results when using
NOT
:
right‐hand side
result
true
false
false
true
multiple Conditions inside an if statement
The previous section started by asking how you could use the condition “Is
degFahren
greater
than zero but less than 100?” One way of doing this would be to use two
if
statements, one nested
inside another.
Nested
simply means that there is an outer
if
statement, and inside this is an inner
if
statement. If the condition for the outer
if
statement is
true
, then (and only then) will the nested
inner
if
statement's condition be tested.
Using nested
if
statements, your code would be:
if (degCent < 100) {
if (degCent > 0) {
document.write("degCent is between 0 and 100");
}
}
This would work, but it's a little verbose and can be quite confusing. JavaScript offers a better
alternative—using multiple conditions inside the condition part of the
if
statement. The multiple
conditions are strung together with the logical operators you just looked at. So the preceding code
could be rewritten like this:
if (degCent > 0 && degCent < 100) {
document.write("degCent is between 0 and 100");
}
The
if
statement's condition first evaluates whether
degCent
is greater than zero. If that is
true
,
the code goes on to evaluate whether
degCent
is less than 100. Only if both of these conditions are
true
will the
document.write()
code line execute.
Multiple Conditions
trY it out
This example demonstrates multi‐condition
if
statements using the
AND
,
OR
, and
NOT
operators. Type
the following code, and save it as
ch3 _ example2.html
:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Chapter 3, Example 2</title>
</head>