Logical operators

The logical operators are used to connect two or more Boolean expressions. Examples of logical operators include the AND operator (&&), OR operator (||), and the NOT operator (!). A condition joined with the AND operator is true only when all of the Boolean expressions are true. For example, in the following

(4 > 2) && (10 < 15)

we have connected two Boolean expressions with the AND operator. For this entire expression to be true, both conditions must be satisfied. Let's first check the first condition. It asks: is 4 greater than 2? The answer is yes, so our first condition is true. In our second condition, we ask: is 10 less-than 15? This condition is also true. Because both of our conditions are true, the entire expression will be evaluated as true.

If, however, one or more conditions joined with an AND operator is false, then the entire expression is false. Consider this example

(4 < 5) && (3 < 2)

This entire expression will be evaluated as false because both conditions are not true. How? The first condition is true because 4 is less than 5. The second condition, however, is not true because 3 is not less than 2. Because one of the conditions is false, our entire expression will be evaluated as false.

In table 2, we list the logical operators available in JavaScript.

Table 2 logical operators
Operator Description
&& Returns true only when all expressions are true.
|| Returns true only when at least one expression is true.
! Returns true if an expression is false, and false if an expression is true.

Table 3 presents a truth table for the AND operator. As the table shows, an expression is true only when both A and B are true; otherwise the expression is false.

Table 3 truth table for the && operator
A B A && B
True True True
True Fasle False
False True False
False False False

Table 4 presents the truth table for the OR operator. As the table indicates, the expression is false only when both of the conditions are false. When at least one of the conditions is true, the resulting expression is true.

Table 4 truth table for the || operator
A B A || B
True True True
True Fasle True
False True True
False False False

Table 5 shows the truth table for the NOT operator. As the truth table shows, the OR operator returns true if the entire expression is false; otherwise the false if the entire expression is true.

Table 5 truth table for the ! operator
A B A ! B
True True False
True Fasle True
False True True
False False True