Question:
I'm studying JavaScript and I have questions about the different ways to do an if
/ else
. For example, this:
foo ? foo : foo
How exactly does it work?
Answer:
Other answers have already explained how the ternary conditional operator works, with good examples. It evaluates conditional expressions, similar to if
:
var variavel = condicao ? valorSeTrue : valorSeFalse;
That is, if the condition (for example x > 5
) is true, the variavel
receives the valorSeTrue
, and if it is false, the valorSeFalse
.
A fundamental difference from if
is that the ternary* is an operator, not a statement . It always results in a value, which is returned as shown in the example. There is no way to initialize a variable on a line with if
precisely because it does not generate any value.
Therefore, the ternary conditional operator is more often 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 variable name. For example, in this assignment with if
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 cargo = salario <= 1000 ? 'junior' : salario <= 5000 ? 'senior' : 'diretor';
If the return value options ( valorSeTrue
valorSeFalse
in my example at the beginning) are function calls, this operator can even be used for flow control:
// Cuidado: código abaixo pode ser péssima prática
// se você não souber o que está fazendo!
validaEmail(email) ? enviaEmail(email) : mostraErro();
In these cases, there are those who defend the exclusive use of this operator instead of if
, especially when programming in functional style (where one could still capture the return of the enviaEmail
or mostraErro
functions, if necessary). I personally feel that each 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 sometimes by the full name, to reinforce it.