Dart Logical Operators
Logical operators in Dart are used to perform logical operations on boolean values. These operators are essential for combining conditional statements and controlling the flow of the program based on multiple conditions. Dart supports three main logical operators:
Overview of Logical Operators
- Logical AND (
&&
) - Logical OR (
||
) - Logical NOT (
!
)
1. Logical AND (&&
)
- Description: The logical AND operator returns
true
if both operands are true; otherwise, it returnsfalse
. - Usage: Often used to combine multiple conditions in control flow statements like
if
.
Example:
2. Logical OR (||
)
- Description: The logical OR operator returns
true
if at least one of the operands is true; otherwise, it returnsfalse
. - Usage: Useful for combining conditions where at least one needs to be true.
Example:
3. Logical NOT (!
)
- Description: The logical NOT operator negates the boolean value of its operand. If the operand is
true
, it returnsfalse
, and vice versa. - Usage: Used to reverse the boolean value of a single condition.
Example:
Combining Logical Operators
Logical operators can be combined to create complex conditional expressions. Here’s an example:
Example:
In this example, the program checks if the person is at least 18 years old and has a valid driver's license.
Truth Table for Logical Operators
| A | B | A && B | A || B | !A | |-------|-------|--------|--------|-------| | true | true | true | true | false | | true | false | false | true | false | | false | true | false | true | true | | false | false | false | false | true |
Summary of Logical Operators
Operator | Description | Example |
---|---|---|
&& | Logical AND | true && false (results in false ) |
` | ` | |
! | Logical NOT | !true (results in false ) |
Conclusion
Logical operators are fundamental in Dart for creating complex conditions and controlling the program flow. They allow developers to make decisions based on multiple criteria, leading to more dynamic and flexible code. Understanding how to use logical operators effectively is essential for writing efficient Dart applications.