In JavaScript, there are three logical operators:
Note: Logical AND and Logical OR are binary operators, whereas logical NOT is a unary operator.
Logical AND operator is represented by the double ampersand (&&). It returns true
if both operands are true
. If one or both operands is false
, then it returns false
.
let result = x && y;
The following truth table shows the result produced by the logical AND operator when applied to the boolean operands.
operand1 | operand2 | operand1 && operand2 |
---|---|---|
true | true | true |
true | false | false |
false | true | false |
false | false | false |
Let's see how to use logical AND operator with the help of an example:
let x = true, y = false; console.log(x && y); //false
Note: To know logical AND operator in detail, visit How to use Logical AND operator in JavaScript?
The double pipe (||) is used to represent Logical OR operator. It returns true
if one or both operands is true
. If both operands are false
, then it returns false
.
let result = x || y;
The following truth table displays the result produced by the logical OR operator when applied to the boolean operands.
operand1 | operand2 | operand1 || operand2 |
---|---|---|
true | true | true |
true | false | true |
false | true | true |
false | false | false |
The following example explains the working of logical OR operator:
let x = true, y = false; console.log(x || y); //true
Note: To learn about logical OR operator in detail, visit How to use Logical OR operator in JavaScript?
In JavaScript, logical NOT is represented by an exclamation point (!).
Logical NOT operator is written before an operand. It returns true
if an operand is a falsy value. If an operand is a truthy value, then it returns false
.
The following code shows how to use logical NOT in JavaScript:
!x
In JavaScript, the following are considered falsy values.
These six values work as a false
value. Apart from the falsy values, all other values are truthy values. For example, objects, arrays, etc. are truthy values
The following table shows the result produced by the logical NOT operator when applied to different JavaScript values.
x | Logical NOT (!x) |
---|---|
true | false |
false | true |
undefined | true |
null | true |
"" is empty string | true |
0 | true |
any number other than 0 | false |
NaN | true |
object | false |
array | false |
The following example shows how to use logical NOT operator:
let x = 123; console.log(!x); //false x = 0; console.log(!x); //true x = [1, 2, 3]; console.log(!x); //false