Ternary Operator in Dart

Ternary Operator in Dart#

Overview#

The ternary operator in Dart provides a concise way to perform conditional operations. It is a shorthand for simple if-else statements and helps reduce code verbosity by combining the conditional logic into a single line.

How It Works#

  • The ternary operator takes the form of condition ? expr1 : expr2.
  • condition is evaluated first; if it is true, expr1 is executed and its result is returned.
  • If the condition is false, expr2 is executed and its result is returned.

Example#

void main() {
  int age = 18;
  
  String result = age >= 18 ? 'Adult' : 'Minor';
  print(result);
}

Overall#

The ternary operator in Dart simplifies conditional expressions by condensing if-else statements into a single line. It evaluates a condition and returns one of two values based on whether the condition is true or false, enhancing code readability and efficiency for straightforward conditional logic.