AND (&&
), Not (!
), OR (||
) are logical operators in Javascript. You will see that they are the only operators that make up for the entirety of one’s life experiences.
Logical operators evaluate two values or expressions, and provide a true
or false
result.
Let us see some examples to know the rules of the game.
AND
Only true
s get along with each other to provide a true result - when dealing with an AND
operation.
|
|
Since any type of variable can evaluate to true
or false
, the above logic can be extended as -
|
|
I am using ‘Boolean’ to ‘cast’ the value to a boolean
and print ‘true’ or ‘false’. This is simpler while doing actual comparison.
See type casting in Javascript to know more. Or, just Google it - that is what I would have done 😜
|
|
One of the best things of an AND
is that Javascript never evaluates the second expression if the first expression is false
.
So, you will find code like the below.
|
|
The code fragment errors out if something
was null and the second expression was moved to the first place.
|
|
OR
Everything is ture
in the ‘OR’ world if at least one of the expressions is true
.
So:
|
|
Extending this further:
|
|
OR will not evaluate the second expression if the first one is true
. Regardless of the second expression, the overall result will be true
if the first expression is true
. (And, the same holds good for false
as well).
NOT
Finally, we come to the negation of/to everything. NOT operator just turns the result on its head - true to false, and false to true.
|
|
You can see that !
is turning everything to Boolean.
And, you already know that ‘opposite of opposite of something’ is ‘something’ represented as simply true
or false
.
Combining the two, we can rewrite expressions used earlier in a more friendly way instead of the explicit Boolean typecasting.
|
|
Go Wild
Logical and comparison operators form one hell of a team. All it takes here on is for you to go wild with the various permutations and combinations of any and all operators.
A glimpse of what is possible:
|
|
Cheerio.