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

OperatorDescriptionLogic
&&Logical ANDReturns true if both expressions are true
||Logical ORReturns true if at least one expression is true
!Logical NOTInverts the boolean value (unary operator)

Code Examples

1. Logical AND (&&)

dart
void main() { bool hasTicket = true; bool hasID = true; if (hasTicket && hasID) { print("Welcome to the flight!"); // Executed } }

2. Logical OR (||)

dart
void main() { bool hasCash = false; bool hasCard = true; if (hasCash || hasCard) { print("Payment accepted!"); // Executed } }

3. Logical NOT (!)

dart
void 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: If A is false, the result is guaranteed to be false. Therefore, B is not evaluated.
  • For A || B: If A is true, the result is guaranteed to be true. Therefore, B is not evaluated.
dart
bool 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.
WhatsApp