Skip to main content
The conditional operator (? :), commonly known as the ternary operator, is an expression that evaluates a boolean condition and returns the result of one of two expressions depending on whether the condition is true or false. It serves as a concise, expression-level alternative to the if-else statement.

Syntax

condition ? expression1 : expression2

Operands

  1. condition: An expression that must evaluate to a type of bool.
  2. expression1: The expression evaluated and returned if condition is true.
  3. expression2: The expression evaluated and returned if condition is false.

Evaluation Logic

The operator utilizes short-circuit evaluation. The runtime process occurs in the following order:
  1. The condition is evaluated.
  2. If the condition is true, expression1 is evaluated and its value becomes the result of the operation. expression2 is not evaluated.
  3. If the condition is false, expression2 is evaluated and its value becomes the result of the operation. expression1 is not evaluated.

Type Inference

The static type of the entire conditional expression is determined by the least upper bound (LUB) of the types of expression1 and expression2.
  • If both expressions are of type int, the result is int.
  • If one expression is int and the other is double, the result is num.
  • If the types share no common hierarchy other than Object?, the result is Object? (or dynamic depending on context).

Example

void main() {
  int a = 5;
  int b = 10;

  // Evaluates (a > b). Since false, returns b.
  int max = (a > b) ? a : b; 
  
  print(max); // Output: 10
}
Master Dart with Deep Grasping Methodology!Learn More