Lesson 10 min
Logical Operators
00:00 / 00:00
Logical Operators
Logical operators are used to combine multiple boolean expressions or invert a boolean value. They are critical for complex decision-making rules in control flow.
List of Logical Operators
| Operator | Description | Logic |
|---|---|---|
&& | Logical AND | Returns true if both expressions are true |
|| | Logical OR | Returns true if at least one expression is true |
! | Logical NOT | Inverts the boolean value (unary operator) |
Code Examples
1. Logical AND (&&)
dartvoid main() { bool hasTicket = true; bool hasID = true; if (hasTicket && hasID) { print("Welcome to the flight!"); // Executed } }
2. Logical OR (||)
dartvoid main() { bool hasCash = false; bool hasCard = true; if (hasCash || hasCard) { print("Payment accepted!"); // Executed } }
3. Logical NOT (!)
dartvoid main() { bool isRaining = false; if (!isRaining) { print("Let's go for a walk!"); // Executed } }
Short-Circuit Evaluation
Dart optimizes logical operations using short-circuit evaluation. This means the second operand is only evaluated if the first operand is not sufficient to determine the final result.
- For
A && B: IfAisfalse, the result is guaranteed to befalse. Therefore,Bis not evaluated. - For
A || B: IfAistrue, the result is guaranteed to betrue. Therefore,Bis not evaluated.
dartbool checkHeavyCondition() { print("Running heavy check..."); return true; } void main() { bool isFastCheckFailed = false; // Short-circuit prevents checkHeavyCondition() from running if (isFastCheckFailed && checkHeavyCondition()) { print("Inside"); } print("Done"); // Prints only "Done" }
Summary
- Use
&&(AND) when all conditions must be met. - Use
||(OR) when at least one condition must be met. - Use
!(NOT) to reverse a boolean value. - Short-circuiting saves compute time by avoiding unnecessary evaluation of secondary expressions.