Skip to main content

Overview

The ternary operator (also called the conditional operator) provides a concise way to write simple if-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 true or false
  • 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:
Output:
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

Use the ternary operator for simple conditional assignments. For complex logic with multiple statements, use traditional if-else blocks for better readability.

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:
Nested ternary operators can be hard to read. For complex conditions with multiple levels, consider using traditional if-else statements instead.

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:
This is equivalent to:

Null-Aware Assignment (??=)

Assigns a value only if the variable is null:

Best Practices

  1. Keep it simple: Use ternary operators for straightforward conditional assignments
  2. Maintain readability: If the expression becomes too complex, use if-else instead
  3. Avoid deep nesting: Nested ternary operators can be confusing
  4. Use for assignments: Ternary operators work best when assigning values to variables

Good Use Case

Better with If-Else