What is the correct way to return a "switch" value?

Asked

Viewed 294 times

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;
}
  • 3

    If there are only two options, it makes no sense to use a switch. A line with ? : (ternary) would suffice: $("#OcorrenciaStatus").html( ocoStatus == 'C'?"Concluído":"Aberto");

  • 1

    @Bacco Thanks.

2 answers

7


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

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


As shown in another answer here at Sopt, the ternary has this structure:

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


Just for the record, your code can be written like this too:

if ( ocoStatus == 'C' ) {
   $("#OcorrenciaStatus").html("Concluído");
} else if ( ocoStatus == 'A' ) {
   $("#OcorrenciaStatus").html("Aberto");
} 

4

Well, the 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;
}

To key-word break after the execution of the code within one of the possible outcomes of the condition, there is a jump out of the switch.

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

There is also the possibility of determining a single instruction 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 the default is optional, however, it is interesting, for once again a matter of semantics, to use it.

The @Bacco left a reply, in his comment, very consistent for your case. But, I decided to leave this answer only as something more enlightening.

Browser other questions tagged

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