Skip to Content
JavaScript: The Definitive Guide, Fourth Edition
book

JavaScript: The Definitive Guide, Fourth Edition

by David Flanagan
November 2001
Intermediate to advanced
936 pages
68h 43m
English
O'Reilly Media, Inc.
Content preview from JavaScript: The Definitive Guide, Fourth Edition

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 ...

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.
Start your free trial

You might also like

JavaScript: A Beginner's Guide, Fourth Edition, 4th Edition

JavaScript: A Beginner's Guide, Fourth Edition, 4th Edition

John Pollock
JavaScript Cookbook, 3rd Edition

JavaScript Cookbook, 3rd Edition

Adam D. Scott, Matthew MacDonald, Shelley Powers

Publisher Resources

ISBN: 0596000480Supplemental ContentCatalog PageErrata