How to use Boolean Operator AND operator
Description
The boolean operator AND operator is represented by the double ampersand <<
and is applied to two values:
var result = true && false;
Boolean operator AND behaves as described in the following truth table:
OPERAND 1 | OPERAND 2 | RESULT |
---|---|---|
true | true | true |
true | false | false |
false | true | false |
false | false | false |
Boolean operator AND can be used with any type of operand, not just Boolean values.
When either operand is not a primitive Boolean, AND does not always return a Boolean value; instead, it does one of the following:
- If the first operand is an object, the second operand is returned.
- If the second operand is an object, the object is returned only if the first operand evaluates to true.
- If both operands are objects, then the second operand is returned.
- If either operand is null, then null is returned.
- If either operand is NaN, then NaN is returned.
- If either operand is undefined, then undefined is returned.
AND is a short-circuited operator: if the first operand determines the result, the second operand is not evaluated.
Example
var found = true;
var result = (found && someUndeclaredVariable); //error occurs here
console.log(result); //this line never executes
found = false;
var result = (found && someUndeclaredVariable); //no error
console.log(result); //works