Ternary Expression

2025/12/27

Type
Learning Resource
Format
Glossary Article
Version
General
Subject Tags
Code
Assets
All else
Copyright 2016-2026, GDQuest
Created
2026/02/16
Updated
2025/12/27

Ternary Expression

A ternary expression is a conditional expression that evaluates to a boolean value. It is also referred to as a "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 use 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_response == "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 other 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_response == "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.

Become an Indie Gamedev with GDQuest!

Don't stop here. Step-by-step tutorials are fun but they only take you so far.

Try one of our proven study programs to become an independent Gamedev truly capable of realizing the games you’ve always wanted to make.

Nathan

Founder and teacher at GDQuest
  • Starter Kit
  • Learn Gamedev from Zero
Check out GDSchool

You're welcome in our little community

Get help from peers and pros on GDQuest's Discord server!

20,000 membersJoin Server

Contribute to GDQuest's Free Library

There are multiple ways you can join our effort to create free and open source gamedev resources that are accessible to everyone!