Logical Expressions
The logical operators &&, ||, and !
perform Boolean algebra and are often used in conjunction with the
relational operators to combine two relational expressions into one
more complex expression. These operators are described in the
subsections that follow. In order to fully understand them, you may
want to review the concept of “truthy” and “falsy” values introduced
in Boolean Values.
Logical AND (&&)
The && operator can
be understood at three different levels. At the simplest level, when
used with boolean operands, && performs the Boolean AND
operation on the two values: it returns true if and only if both its first operand
and its second operand are true. If one or both of these operands is
false, it returns false.
&& is often used as
a conjunction to join two relational expressions:
x==0&&y==0// true if, and only if x and y are both 0
Relational expressions always evaluate to true or false, so when used like this, the
&& operator itself
returns true or false. Relational operators have higher
precedence than && (and
||), so expressions like these
can safely be written without parentheses.
But && does not
require that its operands be boolean values. Recall that all
JavaScript values are either “truthy” or “falsy.” (See Boolean Values for details. The falsy values are false, null, undefined, 0, -0,
NaN, and "". All other values, including all
objects, are truthy.) The second level at which && can be understood is as a Boolean AND operator for truthy and falsy ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access