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

97

I am studying JavaScript and I have doubts about the different ways of doing if / else . For example, this:

foo ? foo : foo

How exactly does it work?

    
asked by anonymous 08.02.2014 / 18:15

7 answers

86

Other answers have explained how the ternary conditional operator , with good examples. It evaluates conditional expressions, much like if :

var variavel = condicao ? valorSeTrue : valorSeFalse;

That is, if the condition (for example x > 5 ) is true, the variavel gets the value valorSeTrue , and if it is false, the valorSeFalse value.

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 seen in the example. You can not initialize a variable on a line with if just because it does not generate any value.

Therefore, the ternary conditional operator is most often used for assigning value to a variable, while the common if f is more commonly used for flow control.

The advantage of the ternary for value assignment is clear: you do not have to repeat the name of the variable. 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;

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, since 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 start example) 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 you could still capture the return of the enviaEmail or mostraErro functions, if necessary). I personally think each one has its place, and I generally 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 by the full name, to reinforce.

    
08.02.2014 / 19:38
38

What you have is a ternary conditional operator , an if / else variant, very common not only in JavaScript.

  

The syntax is: [condition to test] ? [response if 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 (ie, other than 0 , false , null , undefined ) then a receives the value of cat , if false it receives the value of mouse

Example 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 for referring to this detail that I 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).

This can be used

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

Javascript Conditional 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 that toggles between values, there are still uses of logical operators, which can act in place of some ternary tests, especially the logical operator OR which in this case assumes the name of "coalescence operator": anulável || valor-padrão . We can also cite, ways of if without using if, which consists of using an associative map between values and answers, and do not use any if or switch.

Flow Controller Structures

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

if

if is a flow control structure based on a condition, which always has a statement / execution block for when the condition is true, and can optionally display a statement / block for when it is false.

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

Syntax according to MDN :

  

if (condition)
  statement1
  [else
  statement2]

switch

Since switch is a flow control structure that allows you to divert the execution to one of several points, depending on the value of an expression. Each offset point is labeled with a case valor: label, or the default 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 values.

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 break keyword is used to exit the block switch at the end of each section. This is done because the javascript would continue to execute the following label in the break .

Switch syntax in MDN

A switch with% s of% s at the end of each run, is equivalent to% s of% s in chain. 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, you will occasionally find the operator of coalescence.

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

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

The collation operator is used to indicate a default value if a be evaluated as false. Its use is made when a variable can have the value aborted:

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

jsfiddle

This is equivalent 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 crazy things with operators

a && metodo();

is equivalent to

if (a) metodo();

This bizarre way of making an if, even if it seems useless, finds reasonable use in minification of script files . In minified files, this technique saves 2 characters.

jsfiddle ← this fiddle is not running by itself, so press Run that will work!

Using arrays and associative maps instead of ifs

Using arrays and associative maps instead of ifs is a good practice. which can make the program easier to enter, mainly when you notice that there are many if / switch structures repeating 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 switchs, we can do this:

// 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 it actually makes the program easier to understand ... use names descriptions also helps.

Note also that this technique makes it difficult to indicate a pattern, such as% with break . We could do as follows, but there the readability will get a bit shaken (which is lousy):

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

jsfiddle

    
09.02.2014 / 13:10
17

This form of if-else is known as the ternary conditional operator. It is common in many languages, not just for javascript.

The advantage of this format is that you do an if-else on a line and form it neatly.

The format is:

  

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

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

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

Now compare with:

if (input < 40)
    x = 40;
else
    x = input;
    
08.02.2014 / 18:26
14

This is a ternary operator. See official MDN documentation

Although it may complicate the readability of code, 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

  • Not mandatory, although it may improve readability, use of parentheses. But only ?:
  • Useful when condition, true situation and false situation fit in a line, otherwise if-else traditional works
  • Nesting another ternary condition is not recommended in most languages
08.02.2014 / 18:20
8

Ternary, binary and unary

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

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

Above,anexampleofabinaryoperation.Itconsistsoftwooperands,XandY,andresultsinasinglevalue.

TheconditionalJavaScriptoperator

  

Theconditional(ternary)operatoristheonlyJavaScriptoperatorthathasthreeoperands.Thisoperatorisoftenusedasashortcuttotheifstatement. Source.

JavaScript has a single ternary operator, which is the conditional operator. It is often called the ternary operator, because it is the only language. It is not The ternary operator, but A ternary operator.

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

So, about the conditional JavaScript operator, ?: , as many of the answers have already exemplified:

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

We read: 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 ?: . In some SQL dialects there is BETWEEN , which is a ternary operator:

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

See that it is a ternary because it makes an operation composed of three items and evaluates them in one, which in this case is true or false.

Unary operations in JavaScript

JavaScript, like most C-like languages, has these unary operators. They get an operand, X , and result in only Y .

i++ // incremento
i-- // decremento
-i  // negativo
+i  // positivo
!i  // negação
    
17.08.2018 / 01:58
-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*/
    
24.06.2017 / 03:05