See all glossary terms

Ternary Expression

A ternary statement is a statement with a conditional expression that evaluates to a boolean value. It is also referred to as "conditional expression", "ternary operator", or sometimes "inline if". It is a shorthand way of writing an if statement. It is written as follows:
var result = value_if_true if condition else value_if_false
For example:
var player_expression := "normal" if health > 5 else "hurt"
In this example, player_expression will be "normal" if the variable health is greater than 5, and "hurt" otherwise.
Ternary expressions can be combined, at the cost of readability. For example:
var player_expression := "normal" if health > 5 else "hurt" if health > 2 else "dead"
It might be more readable to break down the lines and using parentheses to make the order of evaluation explicit:
var player_expression := "normal" \
  if health > 5 \
  else \
  ( "hurt" \
    if health > 2 \
    else "dead"
  )
For something like this, you would probably use an if statement or a match statement instead, but this style can be useful when coding in a "branchless" way, and ensuring a variable always has a value. Consider the below:
var user_message = null
if server_reponse == "ok":
  user_message = "Success! You're connected"
elif server_response == "error":
  user_message = "Error! Couldn't connect"
In this case, if the server answers something else than "ok" or "error", user_message will be null. We can use a ternary expression to ensure user_message always has a value:
var user_message := "Success! You're connected" \
  if server_response == "ok" \
  else "Error! Couldn't connect"
But even then, it's probably better to code defensively
A potentially more useful way to avoid the above snag is to do this:
var user_message := "Error! Couldn't connect"
if server_reponse == "ok":
  user_message = "Success! You're connected"
This way, if the server response is neither "ok" nor "error", user_message will still have a value.

See Also

Related terms in the Glossary