Menu
Coddy logo textTech

Conditional Operator

Part of the Fundamentals section of Coddy's Dart journey — lesson 30 of 94.

The conditional operator (?:) provides a concise way to write if-else statements in one line:

condition ? expressionIfTrue : expressionIfFalse

Example:

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

Output: Adult

It works with different data types and is ideal for simple conditional assignments.

challenge icon

Challenge

Easy

Create a program that uses the conditional operator (?:) to determine if a player has enough points to level up in a game:

  1. Declare an integer variable playerScore with a value of 750
  2. Declare an integer variable levelUpThreshold with a value of 500
  3. Use the conditional operator to create a string message that says either:
    • "Level up!" if the player's score is greater than or equal to the threshold
    • "Keep trying!" if the player's score is less than the threshold
  4. Store this message in a string variable called message
  5. Print the player's score with the format: Player score: 750
  6. Print the message
  7. Update the player's score to 450
  8. Use the conditional operator again to update the message based on the new score
  9. Print the updated player's score with the format: Player score: 450
  10. Print the updated message

Your output should match the expected format exactly.

Cheat sheet

The conditional operator (?:) provides a concise way to write if-else statements in one line:

condition ? expressionIfTrue : expressionIfFalse

Example:

int age = 20;
String status = age >= 18 ? 'Adult' : 'Minor';

It works with different data types and is ideal for simple conditional assignments.

Try it yourself

void main() {
  // Declare your variables here
  int playerScore = _;
  int levelUpThreshold = _;
  
  // Use conditional operator to create the first message
  String message = playerScore >= levelUpThreshold ? _ : _;
  
  // Print player score and message
  print("Player score: $playerScore");
  print(message);
  
  // Update player score
  playerScore = _;
  
  // Use conditional operator to update the message
  message = playerScore >= levelUpThreshold ? _ : _;
  
  // Print updated player score and message
  print("Player score: $playerScore");
  print(message);
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals