Logical operators allow you to perform logical operations on boolean values. They let you combine, negate, or compare Boolean values and make logical decisions in your code based on the result.
Logical AND (&&) Operator
The AND (&&) operator is a logical operator that returns true if both operands evaluate to true and false otherwise.
In this example, result_1 evaluates to true because two operands in the expression evaluate to true. However, result_2 evaluates to false because the first operand (a > b) returns false.
However, if the first operand is true, the expression proceeds to evaluate the second operand. If the second operand is true, it returns it.
In this example, result_1 evaluates to “hello” because both operands in the expression are true. However, result_2 short-circuits and returns zero without evaluating the second operand.
Note that if there are more operands, the AND operator will continue to evaluate them until it encounters a false value. If it does not encounter any false values, it returns the last true value it encountered.
logical or (||) operator
The OR (||) operator is a logical operator that returns true if and only if one or more of its operands is true. It only returns false when both operands are false.
In the above example, result_1 evaluates to true because both operands in the expression evaluate to true. result_2 evaluates to true because the second operand evaluates to true. result_3 evaluates to false because two operands in the expression evaluate to false.
When the expression is evaluated, if the first operand is true, the operator short-circuits and returns it. However, if it is false, it moves on to evaluate the next operand until it encounters a true operand. If the expression has no truth operands, it returns the last false value it encounters.
In the above example, the NOT operator returns the inverse value of the Boolean operand. When you use the NOT operator in non-Boolean contexts (Result_1 and Result_2), it converts TRUE values to the inverse of TRUE and FALSE values to the inverse of FALSE.
null coalescing (??) operator
The null coalescing operator is a logical operator that evaluates two operands and returns the first operand if it is not null or undefined. Otherwise, it returns the second operand.
At a glance, the null coalescing operator may seem similar to the logical OR (||) operator, but it is not. The main difference is that the OR operator returns the right-hand operand if the left operand is “any” a false value, not just null or undefined.
It provides a concise way to choose a default value when null or undefined values are encountered.