Logical operators are typically used with Boolean (logical) values; when they are, they return a Boolean value. However, the && and || operators actually return the value of one of the specified operands, so if these operators are used with non-Boolean values, they may return a non-Boolean value.
The logical operators are described in the following table.
Examples of expressions that can be converted to false are those that evaluate to null, 0, the empty string (""), or undefined.
Even though the && and || operators can be used with operands that are not Boolean values, they can still be considered Boolean operators since their return values can always be converted to Boolean values.
As logical expressions are evaluated left to right, they are tested for possible "short-circuit" evaluation using the following rules:
false && anything is short-circuit evaluated to false.
true || anything is short-circuit evaluated to true.
The rules of logic guarantee that these evaluations are always correct. Note that the anything part of the above expressions is not evaluated, so any side effects of doing so do not take effect.
The following code shows examples of the && (logical AND) operator.
a1 = true && true; // t && t returns true
a2 = true && false; // t && f returns false
a3 = false && true; // f && t returns false
a4 = false && ( 3 == 4 ); // f && f returns false
a5 = "Cat" && "Dog"; // t && t returns Dog
a6 = false && "Cat"; // f && t returns false
a7 = "Cat" && false; // t && f returns false
The following code shows examples of the || (logical OR) operator.
o1 = true || true; // t || t returns true
o2 = false || true; // f || t returns true
o3 = true || false; // t || f returns true
o4 = false || ( 3 == 4 ); // f || f returns false
o5 = "Cat" || "Dog"; // t || t returns Cat
o6 = false || "Cat"; // f || t returns Cat
o7 = "Cat" || false; // t || f returns Cat
The following code shows examples of the ! (logical NOT) operator.
n1 =! true; // !t returns false
n2 =! false; // !f returns true
n3 =! "Cat"; // !t returns false