JavaScript » Logical

The logical operators are generally used with Boolean values and, when they are, they return a Boolean value. However, both && and || actually return the value of one of their operands, so if the relevent operand is not a Boolean value, the operator may return a non-Boolean value.


&& Operator


This is the logical AND operator, which returns a Boolean true if both the operands are true. Logically it follows that if the first operand is false, then the whole expression is false, and this is how the operator works; It first evaluates the left hand operand, and if this returns false then, without going any further, it returns false for the whole expression. Otherwise it returns the value of the second operand: true or false for a Boolean value, or the actual value itself if nonBoolean.

Examples

Code:
if((a == c) && (b == 5))
x = "bread" && (c == 3)
Explanation:

Assuming 'a' to be 3, 'b' to be 5, and 'c' to be 3, the following examples all return true.

Code:
x = (b > c) && "cheese"
x = "bread" && "cheese"
Explanation:

...while the following return 'cheese':.


|| Operator


This is the logical OR operator and it returns a value of true if one or both of the operands is true. It works by first evaluating the left-hand operand and, if this is true, disregarding the righthand one and returning true for the whole expression. If, however, the left-hand operand is false, then it returns the value of the right-hand operand: true or false if Boolean, or else the value itself.

Examples

Code:
if((a == c) || (b == 9))
x = (a > b) || (c == 3)
Explanation:

These above examples both return true.

Code:
x = (a > b) || "cheese"
Explanation:

...while this one returns 'cheese'.

Code:
x = "bread" || (c == 3)
Explanation:

If, however, the first operand is not a Boolean value, the OR operator returns the value of the first operand whether the second is true or not; in the above example 'bread'.

! Operator

Examples

This is the logical NOT operator which returns false if its single operand can be converted to true, or if it is a non-Boolean value.

Code:
x = !(a == c)
x = !"cheese"
Code:
x = !(a > b)
Explanation:

If its operand can be converted to false.