What is the correct way to return a switch value?

4

How is the correct way to return the value of switch ?

HTML:

<h3 id="txtOcorrenciaStatus">Status</h3>

Javascript:

switch(ocoStatus) {
   case C:
      $("#OcorrenciaStatus").html("Concluído");
      break;
   case A:
      $("#OcorrenciaStatus").html("Aberto");
      break;
}
    
asked by anonymous 27.12.2015 / 21:30

2 answers

7

For the specific case of your code, with only two options, it would not make much sense to use a switch. A line with only ? : (ternary) would suffice:

$("#OcorrenciaStatus").html( ocoStatus == 'C'? "Concluído" : "Aberto" );


As already shown in another answer here in SOpt , the ternary has this structure:

condição/valor verdadeiro ou falso ? retorno se verdadeiro : retorno se falso


Just to state, your code can be written like this too:

if ( ocoStatus == 'C' ) {
   $("#OcorrenciaStatus").html("Concluído");
} else if ( ocoStatus == 'A' ) {
   $("#OcorrenciaStatus").html("Aberto");
} 
    
27.12.2015 / 21:59
4

Well, switch has this structure:

switch (expression) {
  case value1:
    //Instruções executadas quando o resultado da expressão for igual á value1
    break;
  case value2:
    //Instruções executadas quando o resultado da expressão for igual á value2
    break;
  ...
  case valueN:
    //Instruções executadas quando o resultado da expressão for igual á valueN
    break;
  default:
    //Instruções executadas quando o valor da expressão é diferente de todos os cases
    break;
}

key-word break causes that, after running the code within one of the possible results of the condition, there is a jump out of switch .

This method is used for an expression that can result in a number of cases, such as choosing a day of the week. It's more of a semantic issue. Since many ifs , elses may make the code somewhat unreadable.

There is also the possibility of determining a single statement for more than one case, for example:

switch (expression) {
  case value1:
  case value2:
  case value3:
    //Instruções executadas quando o resultado da expressão for igual á value 1, value 2 ou value 3.
    break;
  ...
  case valueN:
    //Instruções executadas quando o resultado da expressão for igual á valueN
    break;
  default:
    //Instruções executadas quando o valor da expressão é diferente de todos os cases
    break;
}

It is worth remembering that default is optional, however, it is interesting, for once again a matter of semantics, to use it.

@Bacco left an answer, in your comment, very consistent for your case. But I decided to leave that answer only as something more enlightening.

    
27.12.2015 / 21:54