Comparison and logical operators
A comparison operator is used to test for a certain relationship between its two operands. If the designated relationship exists, the comparison operator will return True. Conversely, if the two operands don't share the designated relationship, the comparison operator returns False. Using comparison operators, you can test for equality (==), greater than (>), less than (<), greater than or equal to (>=), less than or equal to (<=) or not equal to (!=) relationships. Consider the following examples:
1 = = 1 |
True -- one is equal to one |
2 < 5 |
True -- two is less than five |
6 >= 9 |
False -- six is not greater than or equal to nine |
4 != 3 |
True -- four is not equal to three |
|
It is often necessary to check whether a more complex situation exists, requiring that one of two relationships, or both, exist. To construct more complex conditional expressions, you have to use logical operators. JavaScript has three logical operators, logical AND (&&), logical OR (||) and logical NOT (!).
The logical operators require that their operands be Boolean (True/False) values. The logical AND returns True if and only if both operands are true. The logical OR, however, will return True if either operand or both are True. The following examples will illustrate the use of the logical operators:
True && True |
True -- both operands are true |
False || False |
False -- neither operand is true |
!False && True |
True -- both operands are true (!False is equal to True) |
False && True |
False -- one operand is False |
(2 > 5) || (5 <= 10) |
True -- one operand is True (five is less than or equal to 10) |
|