Green Files

How does if/else with "?" and ":" work?

Day: 06/01/2022 - Time: 14:36:38

Other answers have already explained how the ternary conditional operator works, with good examples. It evaluates conditional expressions, similar to if:

var variable = condition ? valueIfTrue : valueIfFalse;

That is, if the condition (for example x > 5) is true, the variable receives the valueIfTrue value, and if it is false, the valueIfFalse value.

A key difference from if is that the ternary* is an operator, not a statement. It always results in a value, which is returned, as seen in the example. There is no way to initialize a variable in a line with if precisely because it does not generate any value.

That's why the ternary conditional operator is more commonly used for assigning a value to a variable, while the common if is more used for flow control.

The advantage of the ternary for value assignment is clear: there is no need to repeat the name of the variable. For example, in this if assignment we use 6 lines (including the variable declaration):

var x; if(foo) { x = 10; } else { x = 20; }

Or, at best, two lines:

var x = 20; if(foo) x = 10;

With the operator, you can declare, apply the conditional and assign in a single line:

var x = foo ? 10 : 20;

The ternary conditional operator is recommended for simple cases, as complex or nested conditions can make the code difficult to read:

var jobtitle = salary <= 1000 ? 'junior' : salary <= 5000 ? 'senior' : 'diretor';

If the return value options (ValueIfTrue and ValueIfFalse in my example at the beginning) are function calls, this operator can even be used for flow control:

// Caution: code below may be bad practice // if you don't know what you're doing! validEmail(email) ? sendEmail(email) : showError();

In these cases, there are those who defend the exclusive use of this operator instead of the if, especially when programming in a functional style (where you could still capture the return of the sendEmail or showError functions, if necessary). I personally think that each one has its place, and in general I prefer to use ternary for assignments, and if for flow control.

*The ternary conditional operator is popularly known simply as "ternary", or "ternary operator". It is ternary because it has 3 arguments (the condition and the two possible values), but the quality of being conditional can be seen as more relevant, since it deals with its function. In this answer, I chose to call it sometimes just "ternary", for simplicity, and other times by the full name, to reinforce.