🎓 A1Learner
🔍
0 of 52 lessons completed

Julia Ternary Operators

A ternary operator picks one of two values based on a condition. It writes a short choice in a single expression.

A ternary pick can be stored in a variable

The age check is true, so the first value is stored. Printing the variable shows the pick.

age = 20
label = age >= 18 ? "Adult" : "Child"
println(label)

A ternary pick works inside println

The score check is false, so println receives the second value. Only that word prints.

score = 47
println(score >= 50 ? "Pass" : "Fail")

A ternary pick can test a remainder

Seven has a remainder of 1 when divided by 2. The pick is therefore the second word.

n = 7
kind = n % 2 == 0 ? "even" : "odd"
println("7 is $kind")

Example

temperature = 31
feeling = temperature >= 30 ? "hot" : "mild"
println(feeling)
println(temperature >= 30 ? "Drink water" : "Enjoy")

Key points

  • Ternary operator: a short expression written as condition ? first value : second value.
  • Condition: the part before the question mark gives true or false.
  • True branch: the value after the question mark is picked when the condition is true.
  • False branch: the value after the colon is picked when the condition is false.
  • Result: the whole expression gives one value, so it can be stored in a variable.
  • Use it for short picks between two values.

In this example, temperature is 31, so the check temperature >= 30 is true. The first ternary stores the word hot in feeling and the program prints it. The second ternary sits inside println and picks the first message.

Note

A ternary choice is an expression, while an if statement is a block that runs code.

Try it Yourself

Edit the code, then press Run.

Running is simulated · JuliaHub

Exercise

What is the value of x after this code runs? x = 3 > 2 ? 10 : 20