Ad space (banner)
๐ŸŸฃJulia Lessons
Lesson 15 / 68

The ternary operator

This lesson covers Julia's ternary operator, with the aim of expressing a branch concisely on one line.

condition ? value_if_true : value_if_false expresses a simple if statement on one line. It suits short branches such as deciding a message from whether someone is an adult.

The sample code assigns an age-dependent message to message in the single line age >= 20 ? "Adult" : "Minor". Fitting into one line what an if statement would spread over several is its great advantage.

A common early stumble is overusing it until the code becomes hard to read. Cramming a complicated condition in makes things worse, so keep it for simple two-way choices.

In professional work, the ternary operator is used for straightforward assignments and for picking between two messages.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run Julia directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)