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 ? expressionIfTrue : expressionIfFalse
  • 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:
void main() {
  //Operadores Ternarios

  int edad = 26;
                                    
  String mensaje = edad >= 18 ? 'Eres mayor' : 'Eres menor';
  print(mensaje);  // Salida: Eres mayor
}
Output:
Eres mayor
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

int age = 20;
String status;

if (age >= 18) {
  status = 'Adult';
} else {
  status = 'Minor';
}
print(status);  // Output: Adult

Using Ternary Operator

int age = 20;
String status = age >= 18 ? 'Adult' : 'Minor';
print(status);  // Output: Adult
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

int score = 75;
String result = score >= 60 ? 'Pass' : 'Fail';
print(result);  // Output: Pass

Setting Default Values

String? username;
String display = username != null ? username : 'Guest';
print(display);  // Output: Guest

Pricing Logic

bool isMember = true;
double price = isMember ? 9.99 : 14.99;
print('Price: \$${price}');  // Output: Price: $9.99

Even or Odd

int number = 7;
String type = number % 2 == 0 ? 'Even' : 'Odd';
print('$number is $type');  // Output: 7 is Odd

Nested Ternary Operators

You can nest ternary operators, but be cautious as it can reduce readability:
int score = 85;
String grade = score >= 90 ? 'A' :
               score >= 80 ? 'B' :
               score >= 70 ? 'C' :
               score >= 60 ? 'D' : 'F';
print(grade);  // Output: B
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:
String? name;
String displayName = name ?? 'Anonymous';
print(displayName);  // Output: Anonymous
This is equivalent to:
String displayName = name != null ? name : 'Anonymous';

Null-Aware Assignment (??=)

Assigns a value only if the variable is null:
String? title;
title ??= 'Untitled';
print(title);  // Output: Untitled

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

String message = isOnline ? 'Available' : 'Offline';

Better with If-Else

// Too complex for ternary
if (user.isAdmin) {
  print('Welcome Admin');
  logAccess();
  loadAdminPanel();
} else {
  print('Welcome User');
  loadUserPanel();
}

Build docs developers (and LLMs) love