Logical Operators
We have seen that comparison operators like < , >= , ==, etc. operate on numbers (or strings) and result in Boolean values.
Consider the folllowing Logical Operators:
&& and
|| or
! not
These operators also result in Boolean values, but the operands are also Boolean expressions!
(3<4) && (1==2) (result is false)
You can probably reason why the above expression is false. For an "and expression" to be true, both operands need to be true.
But the precise nature of logical operators is not obvious unless you have had a course in introductory logic.
Truth tables like the following are standard in any intro course in logic and explain how the logical operators work in JavaScript.
The following summaries of the above truth tables should make sense if you stop and think about it for a minute.
-
An "and expression" is only true if both operands are true.
P and Q both have to be true, or the whole expression is false.
That's how the conjunction "and" works in everyday speech.
-
An "or expression" is only false if neither of the operands are true.
All it takes is one of P or Q to be true (or both) to make the whole expression true.
-
The "not" operator simply produces the opposite truth value -
"not true" is false , "not false" is true , "not (not true) is true.
The logical operators are often used to deduce a quantity stored in a variable.
Suppose for example, that a variable named num
is populated by a number entered by a user in a prompt window.
(0 < num) && (num < 10 ) true only if num is strictly between 0 and 10
(num < 0) || (num > 10 ) true only if num is NOT between 0 and 10, inclusive
But you have to be careful. It's up to the human to think through the logic very carefully.
For example, if you switch the and/or in the above expressions, unexpected results happen.
(0 < num) || (num < 10 ) OOPS - always true, for any value in num
(num < 0) && (num > 10 ) OOPS - always false, for any value in num
Remember, a computer simply executes your instructions, whether logical or not.