Language: EN

programacion-operador-ternario

The ternary operator

The ternary conditional, also known as ternary operator, is a control structure that allows evaluating a condition and returning a value based on that condition.

The ternary operator is called that because, in general, it is the only operator in a language that has three parameters. The others usually have one parameter, such as the negation operator !myvariable or two, like the sum operators a+b

Unlike the conditionals IF-ELSE, 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, true_value is returned
  • If it is true, false_value is returned

This structure is very useful when it is necessary to assign a value to a variable or perform a simple operation based on a condition.

As in the rest of the conditionals condition has to be an expression that evaluates to a boolean value. That is, it has to be one of the following expressions,

  • false or true
  • A boolean variable
  • An expression that evaluates as boolean
  • The call of a function that returns a boolean

Equivalent in IF-ELSE

If we make the equivalent in an IF-ELSE block of the ternary operator, it would look something like this.

let result

if(condition)   result = value_if_true
else            result = value_if_false

As we can see, it is (slightly) longer.

Examples of ternary operator in different languages

As I said, many languages implement the ternary operator as a comparison form.

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 a minor";

In this example, we use the ternary conditional in C# to assign a message according to the age. If the age is greater than or equal to 18, the message “You are of legal age” is assigned, otherwise the message “You are a minor” is assigned.

In JavaScript the ternary operator is identical. In the example, the only difference is that JavaScript does not declare the type of the variables, but the syntax of the conditional is the same.

let age = 18;
let result = age >= 18 ? "You are of legal age" : "You are a minor";

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 a minor"

For example, in SQL the ternary operator does not exist, and instead a IFF function is provided that fulfills the same role.

IFF(@type = 2, 1, 0)

Nesting of ternary operators

Like the rest of the operators, the ternary conditional can be chained. With this, more complex conditionals can be generated, such as for example.

let condition1 = false;
let condition2 = true;
let b = condition1 ? 'true1' 
      : condition2 ? 'true2' 
      : 'false_both';

In some circumstances, this can improve the readability of the code. But it is not convenient to abuse it because, in general, you can build very complicated to read sentences.

Best practices and cleanliness tips 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 does not become too complex.

Avoid nesting ternary operators: Nesting multiple ternary operators can make the code difficult to read. In general, avoid it.

Do not make calls to heavy functions: The ternary operator must always be simple. Do not use it to

var a = validateData() ? value_true : value_false;

Instead, prefer

var isValid = validateData() 
var a = isValid ? value_true : value_false;

Prefer clarity over brevity: Even if the code becomes more readable or less, consider using conditionals IF-ELSE or breaking down the logic into multiple lines to make it clearer and more understandable.

Use parentheses to avoid ambiguities: If you have more complex expressions involving ternary operators, use parentheses to ensure that the evaluation is done correctly and avoid ambiguities in the precedence of operators.

Relationship with the functional paradigm Advanced

It is often said that the ternary conditional follows the personal programming paradigm. Well, that is not exactly true. Let’s say it is “more given” to 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 call a function, we start to approach the red zone.

function function_yes() {
  // I do nothing
  return 'yes'
}

function function_no() {
  // I do nothing
  return 'no'
}

let result = condition ? function_yes() : function_no();

In the previous example, the functions have value but do not perform actions. It is still functional programming, but less than before.

If in this example, instead of returning a value, we perform actions, it would no longer be functional. For example, the following,

function function_yes() {
  // I do things and do not return anything
}

function function_no() {
  // I do things and do not return anything
}

condition ? function_yes() : function_no();

It is not functional at all, no matter how much you are using a ternary conditional. Here the ternary operator is being used to bifurcate code. We are not even using the resolved value.

I’m not saying it’s wrong (for me, it’s not clean, but it’s debatable), what it certainly is not is functional.

So if someday you have a conversation about this, the correct thing is to say “the ternary operator facilitates a functional paradigm”, but it is not functional. It will depend on how we use it.