How does this if/Else work with "?" and ":"?

Asked

Viewed 78,990 times

117

I am studying Javascript and I have doubts about the different ways to make a if/ else. For example, this:

foo ? foo : foo

How exactly does it work?

7 answers

112


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

var variavel = condicao ? valorSeTrue : valorSeFalse;

That is, if the condition (eg x > 5) is true, the variavel receives the amount valorSeTrue, and if false, the valorSeFalse.

A fundamental difference in relation to if is that 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 on a line with if precisely because it generates no value at all.

Therefore, the ternary conditional operator is more commonly used to assign value to a variable, while the if common is most 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 variable declaration):

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

Or, at best, two lines:

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

Already with the operator you can declare, apply the conditional and assign in a single row:

var x = foo ? 10 : 20;

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

var cargo = salario <= 1000 ? 'junior' : salario <= 5000 ? 'senior' : 'diretor';

If the value options to be returned (valorSeTrue and valorSeFalse in my example of 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 the if, especially when programming in functional style (where one could still capture the return of functions enviaEmail or mostraErro, if necessary). I personally think each has its place, and in general I prefer to use the ternary for assignments, and the 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 sometimes only "ternary", for simplicity, and others for the full name, to reinforce.

  • 2

    +1 by stating that this operator returns a value (which can be assigned to a variable, within another ternary or in an if statement.)

  • 7

    In a way it is the best explanation, although it does not give useful examples (because they have already been given). There are people who have prejudice with ternary operator. It is the typical case of "read somewhere that can be less readable and then I will abhor him, as far as he is the best way". You have to understand the foundation of the resource to use it correctly.

  • @bigown I tried to include examples that fit here without repeating the other answers. Think it improved (is more complete) or got worse (more confusing)?

  • It got better. Want an idea? Not that it is so necessary, but in all answers the counterpoint is missing. The example of wrong use. But it’s up to you whether it fits the answer or whether it’s worth the effort.

  • I had never understood these things, and thanks to your reply I was able to understand, beautiful answer. + 1

42

What you have is a ternary conditional operator, a variant of if/Else, very common not only in Javascript.

The syntax is: [ condition to be tested ] ? [ answer if true ] : [ answer if not true ]

Exactly this ternary conditional operator that you showed with foo three times does nothing... but if you have

var a = dog ? cat : mouse;

then if dog is true (i.e., different from 0, false, null, undefined) then a receives the value of cat, if false receives the value of mouse

Example of conditions:

var valor = 10;
valor == 20 ? 'sim' : 'não' // retorna 'não'
valor !=20 ? 'sim' : 'não' // retorna 'sim'
valor < 20 ? 'sim' : 'não' // retorna 'sim'
valor - 10 ? 'sim' : 'não' // retorna 'não' porque 0 é interpretado como false, neste caso melhor usar (valor - 10) == 0 ?

This ternary conditional operator is similar to

if(condição) { //faz algo se a condição for verdadeira }
else { //faz outra coisa caso contrário }

However (and credit to @bfavareto by mentioning this detail that had forgotten to mention), this operator returns a value (which can be assigned to a variable, within another ternary or as a condition of another if statement).

So it can be used

var variavel = foo ? foo : bar;
// ou mesmo, ainda mais comprimido, útil em alguns casos
var variavel = foo || bar;

32

Javascript Conditionals Overview

Javascript is a really interesting language in this regard. In addition to language structures for flow control if/else, switch and others, and also the ternary operator condição ? a : b alternating between values, there are still unusual uses of logical operators, which may act in place some ternary tests, especially the logical operator OR which in that case takes the name of "coalescence operator": anulável || valor-padrão. We can also cite, forms of do if without using if, which consists of using an associative map between values and answers, and use no if or switch.

Structures of Flow Control

I will quote only the linear flow control structures: if and the switch.

if

The if is a flow control structure based on one condition, that always has a statement/execution block for when the condition is true, and can optionally present a statement/block for when it’s fake.

if (condicao) verdadeiro();
else falso();

Syntax according to MDN:

if (condition)
     statement1
[Else
     statement2]

switch

Already the switch is a flow control structure that allows you to deviate execution for one of several points, depending on the value of an expression. Each diversion point shall be marked with a label case valor:, or else the standard label, which is executed when no other is equal to the expression.

Suppose a variable expression, which can assume the values: "small", "medium" and "large" or any other value.

switch (expressao) {

    case "pequeno":
        pequeno();
        break;

    case "médio":
        medio();
        break;

    case "grande":
        grande();
        break;

    default: // não é pequeno, nem médio, nem grande
        tamanhoInvalido();
        break;
}

Note that the keyword is used break, that serves to leave the block switch at the end of each snippet. This is done because javascript would continue executing the portion of the next label in the assistance of the break.

Syntax of the switch on MDN

A switch with breaks at the end of each leg is equivalent to ifs in jail. The previous code could be written like this:

if (expressao == "pequeno") {
    pequeno();
}
else if (expressao == "médio") {
    medio();
}
else if (expressao == "grande") {
    grande();
}
else {
    tamanhoInvalido();
}

Conditional operators

The ternary conditional operator, is the best known, but as if you see codes in javascript, if you occasionally find the operator coalescent.

The ternary operator chooses one of two values based on a.

var mensagem = sexo == 'M' ? "bem vindo senhor" : "bem vinda senhora";

The cholesterol operator, on the other hand, serves to indicate a standard value, if a expression is evaluated as false. Its use is made when a variable may have the value cancelled:

var opcaoDoUsuario = usuario.opcao || "Opção padrão";

jsfiddle

This amounts to the following:

var opcaoDoUsuario = usuario.opcao ? usuario.opcao : "Opção padrão";

Note that this is a way to set a default value for when the value of the variable is null for example, because null is evaluated as false.

Other madness with operators

a && metodo();

amounts to

if (a) metodo();

That bizarre way of doing an if, even though it seems pointless, finds a reasonable use in minification of script files. In minified files, this technique saves 2 characters.

jsfiddle this fiddle is not running alone, so press Run that will work!

Using arrays and associative maps instead of ifs

Using arrays and associative maps instead of ifs is good practice that can make the program easier to understand, mainly when you notice that there are many if/switch structures repeating by code out.

// suponha que 'pequeno', 'medio' e 'grande' são funções
var mapaDeTamanhos = { "pequeno": pequeno, "médio": medio, "grande": grande };

Now in place of the Witches, we can do so:

// suponha que tamanho é uma variável que só pode assumir os valores
// "pequeno", "médio" e "grande"
mapaDeTamanhos[tamanho]();

Obviously you should not do this with all ifs/Switchs, but yes when this actually makes the program easier to understand... use names descriptive also helps.

Note also that this technique makes it difficult to indicate a pattern, such as the deafult of switch. We could do as follows, but then readability will be a little shaken (which is terrible):

// que ver isso vai pensar: "mas que droga é essa?"
// e vai ficar com cara de WTF =\
(mapaDeTamanhos[tamanho] || tamanhoInvalido)();

jsfiddle

  • 2

    your answer is much more than the question; do not think it better to create a question and answer it, and by that answer here?

  • @Emersonrochaluiz The question was not very specific either.

17

This form of if-lse is known as ternary conditional operator. It is common in several languages, not only for javascript.

The advantage of this format is that you make an if-lse on a line and form well clean.

The format is:

< condition > ? < real case > : < false case >;

Example: If I use a ternary conditional operator to limit the value x to always be at a minimum 40, would be:

x = (input < 40) ? 40 : input;

Now compare with:

if (input < 40)
    x = 40;
else
    x = input;

15

That’s a ternary operator. See official documentation on MDN

While it can complicate code readability, in some situations it is extremely useful and succinct.

Example:

// Pseudo código
condicao ? executa-se-verdadeira : executa-se-falsa

// Imprime "1 não é maior que 2"
console.log(1 > 2 ? "1 é maior que 2": "1 não é maior que 2");

Useful recommendations

  • It is not mandatory, although it can improve readability, use of parentheses. But yes only ?:
  • Useful when condition, true situation and false situation fit in a row, otherwise if-else traditional works
  • Nesting another ternary condition is not recommended in most languages

10

Ternaries, binaries and unary

Ternary, of the Latin ternarius, means "composed of three items". Ternary operations, whether in mathematics or in computer science, are those that have three operands.

From this, it can be inferred that there are operations unary, binary and ternary also.

exemplo de operação binária

Above, an example of binary operation. It consists of two operands, X and Y, and results in a single.

The conditional operator of Javascript

The conditional operator (ternary) is the only Javascript operator that has three operands. This operator is often used as a shortcut to the if statement. Source.

Javascript has a single ternary operator, which is the conditional operator. It is often called the ternary operator because it is the only one of the language. It is not The ternary operator, however ONE ternary operator.

resultado = {condição} ? {expressão se verdadeiro} : {expressão se falso}

Therefore, regarding the conditional operator of Javascript, the ?:, as many of the answers have already exemplified:

idade >= 18 ? servirVinho() : servirSuco()

It reads: if idade is greater than or equal to 18, then servirVinho(), otherwise, servirSuco().

Other ternary operators in other languages

But do not think that ternary operations are limited to the ?:. In some SQL dialects there is BETWEEN, which is a ternary operator:

[...] WHERE {campo} BETWEEN {expressão 1} AND {expressão 2}

Note that it is a ternary because it makes an operation composed of three items and evalua in one, which in case is true or false.

Unary operations in Javascript

Javascript, like most languages C-like, have these unary operators. Receive an operand, X, and result in a single Y.

i++ // incremento
i-- // decremento
-i  // negativo
+i  // positivo
!i  // negação
  • 1

    +1 after Edit, is a good explanation of the term, now that it has become a complement using correct terminology..

-3

var a = 10;

//Método padrão 

if(a == 10){
  //Faça isso
}else{
  //Faça isso
}

//Método simplificado

a == 10 ? /*Faça isso*/ : /*Faça isso*/

  • 10

    There is nothing wrong with answering old or already answered questions, but it only makes sense to do so if you add new information or present it differently from the ones already presented. I don’t think that’s the case, so if you think your answer really helps in a way that others don’t, I recommend you edit it and make it as clear as possible by explaining with text the idea you want to pass on, not just code.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.