Logical Operators
The
logical operators are typically used to perform Boolean algebra. They
are often used in conjunction with comparison operators to express
complex comparisons that involve more than one variable and are
frequently used with the if
,
while
, and for
statements.
Logical AND (&&)
When used with boolean
operands, the &&
operator 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
.
The actual behavior of this operator is somewhat more complicated. It
starts by evaluating its first operand, the expression on its left.
If the value of this expression can be converted to
false
(for example, if the left operand evaluates
to null
, 0
,
""
, or undefined
), the operator
returns the value of the lefthand expression. Otherwise, it evaluates
its second operand, the expression on its right, and returns the
value of that expression.[15]
Note that, depending on the value of the lefthand expression, this
operator may or may not evaluate the righthand expression. You may
occasionally see code that purposely exploits this feature of the
&&
operator. For example, the following
two lines of JavaScript code have equivalent effects:
if (a == b) stop( ); (a == b) && stop( );
While some programmers (particularly Perl programmers) find this a natural and useful programming idiom, I recommend against using it. The fact that the righthand side ...
Get JavaScript: The Definitive Guide, Fourth Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.