Java Reference
In-Depth Information
evaluate to
true
, it won't make any difference to the final result—it'll still be
false
. So to avoid
wasting time, if the left‐hand side is
false
, JavaScript doesn't even bother checking the right‐hand
side and just returns a result of
false
.
Or
Just like
AND
,
OR
also works much as it does in English. For example, you might say that if it is
raining
or
if it is snowing, then you'll take an umbrella. If either of the conditions “it is raining” or
“it is snowing” is true, you will take an umbrella.
Again, just like
AND
, the
OR
operator acts on two boolean values (one from its left‐hand side and one
from its right‐hand side) and returns another boolean value. If the left‐hand side evaluates to
true
or the right‐hand side evaluates to
true
, the result returned is
true
. Otherwise, the result is
false
.
The following table shows the possible results:
left‐hand side
right‐hand side
result
true
true
true
false
true
true
true
false
true
false
false
false
As with the
AND
operator, JavaScript likes to avoid doing things that make no difference to the final
result. If the left‐hand side is
true
, then whether the right‐hand side is
true
or
false
makes no
difference to the final result—it'll still be
true
. So, to avoid work, if the left‐hand side is
true
, the
right‐hand side is not evaluated, and JavaScript simply returns
true
. The end result is the same—the
only difference is in how JavaScript arrives at the conclusion. However, it does mean you should not
rely on the right‐hand side of the
OR
operator to be executed.
NOt
In English, we might say, “If I'm
not
hot, then I'll eat soup.” The condition being evaluated is whether
we're hot. The result is true or false, but in this example we act (eat soup) if the result is false.
However, JavaScript is used to executing code only if a condition is
true
. So if you want a
false
condition to cause code to execute, you need to switch that
false
value to
true
(and any
true
value
to
false
). That way you can trick JavaScript into executing code after a
false
condition.
You do this using the
NOT
operator. This operator reverses the logic of a result; it takes one boolean
value and changes it to the other boolean value. So it changes
true
to
false
and
false
to
true
.
This is sometimes called
negation
.
To use the
NOT
operator, you put the condition you want reversed in parentheses and put the
!
symbol in front of the parentheses. For example:
if (!(degCent < 100)) {
// Some code
}