logo

Julia's Ternary Operator ? : 📂Julia

Julia's Ternary Operator ? :

Overview

In Julia, A ? B : C is known as the Ternary Operator, which returns B if A is true and C otherwise. Just like binary operations are defined as functions in mathematics, the ternary operation is also a function. It’s similar to an if statement but has this fundamental difference, making it very useful once you’re accustomed to it. However, it can make the code less readable, so it’s not necessary to overuse it, but since others may use it, it’s good to get familiar with it to some extent.

Code

julia> x = iseven(2) ? "even" : "odd"; x
"even"

julia> y = iseven(3) ? "even" : "odd"; y
"odd"

As seen above, these commands assign the string "even" or "odd" to variables x, y, depending on whether the given number is even or odd.

julia> x * y
"evenodd"

Since it’s a function rather than a conditional statement, it allows for such convenient code. Trying to accomplish the same functionality using only if statements could unnecessarily lengthen the code due to issues like scope.

Complete Code

x = iseven(2) ? "even" : "odd"; x
y = iseven(3) ? "even" : "odd"; y
x * y

Environment

  • OS: Windows
  • julia: v1.6.3