Logical operators perform logical operations: AND, OR and NOT.
Logical OR (||)
|| evaluates to true if either of the operands is true. If both operands are false, the result is false.
Syntax :
let result = a || b;
const a = true, b = false, c = 4;
// logical OR
console.log(a || b); // Output : true
console.log(b || b); // Output : false
The || operator returns false if both values evaluate to false. In case either value is , the || operator returns true. For example:
let message = true,
str = false;
console.log(message || str); // Output : true
A chain of || operators
let result = value1 || value2 || value3;
The || operator does the following:
- Evaluates values from left to right.
- For each value, converts it to a boolean value. If the result of the conversion is true, stops and returns the value.
- If all values have been evaluated to false, returns the last value.
In other words, the chain of the || operators returns the first truthy value or the last one if no truthy value was found.
The Logical AND operator (&&)
JavaScript uses the double ampersand (&&) to represent the logical AND operator. AND returns true if both operands are true. It returns false if one operand from two is false.
Syntax :
let result = a && b;
let message = true,
let str = true;
console.log(message && str); // Output : true
In this example both operands are true therefore result is true.
let message = true,
let str = false;
console.log(message && str); // Output : false
In this example one operand value is false therefore result is false.
let message = false,
let str = false;
console.log(message && str); // Output : false
In this example both operand value is false therefore result is false.
A Chain of && operators
let result = value1 && value2 && value3;
The && operator carries the following:
- Evaluates values from left to right.
- For each value, converts it to a boolean. If the result is false, stops and returns the original value.
- If all values are truthy values, returns the last value.
The Logical NOT operator (!)
JavaScript uses an exclamation point! to represent the logical NOT operator. When you apply the! operator to a boolean value, the! returns true if the value is false and returns false if the value is true.
let message = false,
let str = true;
console.log(!message); // Output : true
console.log(!str); // Output : false