Overview
The ternary operator (also called the conditional operator) provides a concise way to write simpleif-else statements in a single line. It’s particularly useful for conditional assignments and simple decision-making.
Syntax
The ternary operator has three parts:- condition: A boolean expression that evaluates to
trueorfalse - expressionIfTrue: The value returned if the condition is
true - expressionIfFalse: The value returned if the condition is
false
Basic Example
Here’s a complete example using the ternary operator:Since
edad is 26, which is greater than or equal to 18, the condition evaluates to true, so the first expression 'Eres mayor' is returned.Comparison with If-Else
The ternary operator is a shorthand for simple if-else statements.Using If-Else
Using Ternary Operator
Practical Examples
Determining Pass/Fail
Setting Default Values
Pricing Logic
Even or Odd
Nested Ternary Operators
You can nest ternary operators, but be cautious as it can reduce readability:Null-Aware Operators
Dart also provides null-aware operators that work similarly to ternary operators:Null Coalescing (??)
Returns the left value if it’s not null, otherwise returns the right value:
Null-Aware Assignment (??=)
Assigns a value only if the variable is null:
Best Practices
- Keep it simple: Use ternary operators for straightforward conditional assignments
- Maintain readability: If the expression becomes too complex, use if-else instead
- Avoid deep nesting: Nested ternary operators can be confusing
- Use for assignments: Ternary operators work best when assigning values to variables