Java Reference
In-Depth Information
JavaScript enables you to use such multiple conditions. To do this, you need to learn about three more
operators: the logical operators
AND
,
OR
, and
NOT
. The symbols for these are listed in the following table:
operator
sYmbol
AND
&&
OR
||
NOT
!
Notice that the
AND
and
OR
operators are
two
symbols repeated:
&&
and
| |
. If you type just one
symbol,
&
or
|
, strange things will happen because these are special operators called
bitwise
operators
used in binary operations—for logical operations you must always use two.
After you've learned about the three logical operators, you take a look at how to use them in
if
statements, with plenty of practical examples. So if it seems a bit confusing on first read, don't
panic. All will become clear. Let's look at how each of these works, starting with the
AND
operator.
aND
Recall that we talked about the left‐hand side (LHS) and the right‐hand side (RHS) of the operator.
The same is true with the
AND
operator. However, now the LHS and RHS of the condition are
boolean values (usually the result of a condition).
The
AND
operator works very much as it does in English. For example, you might say, “If I feel cold
and
I have a coat, then I'll put my coat on.” Here, the left‐hand side of the “and” word is “Do I feel
cold?” and this can be evaluated as
true
or
false
. The right‐hand side is “Do I have a coat?” which
again is evaluated to either
true
or
false
. If the left‐hand side is true (I am cold)
and
the right‐hand
side is true (I do have a coat), then you put your coat on.
This is very similar to how the
AND
operator works in JavaScript. The
AND
operator actually produces
a result, just as adding two numbers produces a result. However, the
AND
operator takes two boolean
values (on its LHS and RHS) and results in another boolean value. If the LHS and RHS conditions
evaluate to
true
, the result will be
true
. In any other circumstance, the result will be
false
.
Following is a
truth table
of possible evaluations of left‐hand sides and right‐hand sides and the
result when
AND
is used:
left‐hand side
right‐hand side
result
true
true
true
false
true
false
true
false
false
false
false
false
Although the table is, strictly speaking, true, it's worth noting that JavaScript doesn't like doing
unnecessary work. Well, who does! If the left‐hand side is
false
, even if the right‐hand side does