The ternary conditional (also known as the ternary operator) is a control structure that allows evaluating a condition and returning a value based on that condition.
Unlike IF-ELSE conditionals, the ternary conditional is composed of a single line of code and has the following general syntax:
result = condition ? value_if_true : value_if_false
In this expression:
- The condition is evaluated
- If it is
true,value_trueis returned - If it is
false,value_falseis returned
This structure is very useful when you need to assign a value to a variable based on a condition.
As with all other conditionals, condition must be an expression that evaluates to a boolean value. That is, it must be one of the following expressions:
falseortrue- A boolean variable
- An expression that evaluates to a boolean
- A function call that returns a boolean
The ternary operator is called that because, in general, it is the only operator in a language that has three parameters. Others usually have one parameter, like the negation operator !myvariable, or two, like the addition operator a+b
Equivalent in IF-ELSE
If we make the equivalent of the ternary operator in an IF-ELSE block, it would look something like this.
let result
if(condition) result = value_if_true
else result = value_if_false
As we can see, it’s (slightly) longer.
Examples of the ternary operator in different languages
As I said, many languages implement the ternary operator as a form of comparison.
For example, in the case of C, C++, Java and C#, the ternary conditional has the following form,
int age = 18;
string result = age >= 18 ? "You are of legal age" : "You are underage";
In this example, we use the ternary conditional in C# to assign a message according to age. If the age is greater than or equal to 18, the message “Eres mayor de edad” is assigned, otherwise the message “Eres menor de edad” is assigned.
In JavaScript the ternary operator is identical. In the example, only the fact that JavaScript does not declare variable types changes, but the conditional syntax is the same.
let age = 18;
let result = age >= 18 ? "You are of legal age" : "You are underage";
In Python the conditional is somewhat different, and has the following form.
age = 18
result = "You are of legal age" if age >= 18 else "You are underage"
To give a more bizarre example, in SQL the ternary operator does not exist, and instead a function IFF is provided that serves the same purpose.
IIF(@type = 2, 1, 0)
Nesting ternary operators
Like other operators, the ternary conditional can be chained. This allows for more complex conditionals to be created, for example.
let condition1 = false;
let condition2 = true;
let b = condition1 ? 'true1'
: condition2 ? 'true2'
: 'false_both';
In some circumstances, this can improve code readability. But it’s not advisable to overuse it because, in general, you can create statements that are very difficult to read.
Best Practices Tips
Keep it simple and readable: The ternary operator can be useful for expressing conditional logic concisely. However, avoid overusing it and make sure the expression is easy to understand and doesn’t become too complex.
Avoid nesting ternary operators: Nesting multiple ternary operators can make code difficult to read. In general, avoid it.
Don’t call heavy functions: The ternary operator should always be simple. Don’t use it for
var a = validateData() ? value_true : value_false;
Instead, prefer
var isValid = validateData()
var a = isValid ? value_true : value_false;
Prefer clarity over brevity: At the slightest doubt about whether the code becomes more or less readable, consider using IF-ELSE conditionals or breaking down the logic into multiple lines to make it clearer and more understandable.
Use parentheses to avoid ambiguity: If you have more complex expressions involving ternary operators, use parentheses to ensure correct evaluation and avoid ambiguity in operator precedence.
Relationship with the functional paradigm Advanced
It is often said that the ternary conditional follows the functional programming paradigm. Well, that’s not exactly true. Let’s say it is “more inclined” towards functional programming than an IF. But whether it is functional or not depends entirely on how we use it.
For example, if we use it as usual, evaluating a condition and returning one value or another, it is functional programming.
let result = condition ? 'yes' : 'no'
If instead of returning a variable or a literal, I make a function call, we start approaching the red zone.
function function_yes() {
// do nothing
return 'yes'
}
function function_no() {
// do nothing
return 'no'
}
let result = condition ? function_yes() : function_no();
In the previous example, the functions return a value but perform no actions. It’s still functional programming, but less so than before.
If in this example, instead of returning a value, we performed actions, it would no longer be functional. For example, the following,
function function_yes() {
// do things and return nothing
}
function function_no() {
// do things and return nothing
}
condition ? function_yes() : function_no();
That is not functional at all (even though you are using a ternary conditional). Here the ternary operator is being used to create a code branch. We are not even using the resolved value.
I’m not saying it’s incorrect (for me it’s not clean, but that’s debatable). What it certainly is not, is functional.
So if you ever have a conversation about this, the correct thing to say is “the ternary operator facilitates a functional paradigm”, but it is not inherently functional. It will depend on how we use it.
