Javascript logical operators examples
In this article, I would like to discuss javascript logical operators with examples.
What are logical operators?
Logical operators are also known as logical connectives. They are used to connect one or more conditions. They accept Boolean operands, and on evaluation, they yield the result as true or false. There are three types of logical operators in javascript.
&&: Logical AND operator
The pair of ampersand symbols denote the Logical AND operator. If both LHS and RHS operands are true then the result will be true, in all other cases the result will be false
Truth table
p | Q | P&&Q |
---|---|---|
True | True | True |
True | False | False |
False | True | False |
False | False | False |
Example:
document.write((3<4) && (4<5));
document.write((3<4) && (4>5));
document.write((3>4) && (4<5));
document.write((3>4) && (4>5));
/*
Output:
true
false
false
false
*/
||: Logical OR operator
The pair of pipeline symbols denote the Logical OR operator. If both LHS and RHS operands are false then the result will be false, in all other cases, the result will be true.
Truth table
P | Q | P||Q |
---|---|---|
True | True | True |
True | False | True |
False | True | True |
False | False | False |
Example
document.write((3<4) || (4<5));
document.write((3<4) || (4>5));
document.write((3>4) || (4<5));
document.write((3>4) || (4>5));
/* Output:
true
true
true
false */
!: Logical NOT operator
The exclamation mark symbol denotes the Logical NOT or negation operator. If the given operands are false, then the result will be true.
Truth table
P | !P |
---|---|
True | False |
False | True |
Example
document.write( !(3<4));
document.write( !(3>4));
/* Output:
false
true */