How to make a javascript switch

-2

I have several if-else that I need to simplify:

var color = "";
if (tipo == "0") {
   color = "FF0000";
 } else if (tipo == "1") {
   color = "CC9900";
 } else if (tipo == "2") {
   color = "AA0000";
 .... 
 } else {
   color = "000000";
 } 

Is there a way to make switch in javascript ?

    
asked by Jordi Castilla 28.07.2016 в 21:09
source

4 answers

1

You can also use the short function of switch case in the following way:

var color = "";
var miTipo = prompt("Ingrese un numero");
var casos = {
    0: "#FF0000",
    1: "#CC9900",
    2: "#AA0000"    
};
//si hay condicion cumplida
if (casos[miTipo]) {  
  color = casos[miTipo];
}else{
  //Aqui lo que seria el default de un switch case tradicional
  color = "#000000";
}
alert('El color es: ' + color);
    
answered by 28.07.2016 / 21:37
source
1

To do this you can use a switch , although depending on where the variable to identify you must trime it or convert the String in int first or so that no problems:

var color = "";
var typeInt = parseInt(type)
alert(typeInt);
switch(typeInt) {
    case 0:
        color = "#FF0000"
        break;
    case 1:
        color = "#CC9900"
        break;
    case 2:
        color = "#AA0000"
        break;
    default:
        color = "#000000"
}   
    
answered by 28.07.2016 в 21:09
1

A switch is basically a simplification of a strict comparison === in javascript with some added values.

Taking as a starting point the following comparison

if (variable === valor1) {
    // bloque 1 de código
} else if (variable === valor2) {
    // bloque 2 de código
} else if (variable === valor3) {
    // bloque 3 de código
} else {
   // bloque de código si las demás condiciones no se cumplen
}

It translates to

switch(variable) {
    case valor1:
        // bloque 1 de código
        break;
    case valor2:
        // bloque 2 de código
        break;
    case valor3:
        // bloque 3 de código
        break;
    default:
        // bloque de código si las demás condiciones no se cumplen
}

Remember that relaxed comparison == and strict comparison === do not behave the same all the time so you should not use switch if your code depends on some data conversion (or you must convert before running switch ) since this always will use comparison strict.

What are the added values that can be obtained with a switch that can be more complicated to obtain using if ?

  • With switch you can execute more than one block at a time depending on the condition. For this you just have to remove the break instruction and it will continue to the following blocks of code

    switch(variable) {
        case valor1:
            // bloque 1 de código
        case valor2:
            // bloque 2 de código
            break;
        case valor3:
            // bloque 3 de código
            break;
        default:
            // bloque de código si las demás condiciones no se cumplen
    }
    

    In this case, if the variable equals valor1 , both the code in block 1 and block 2 will be executed. This can sometimes help to simplify code. This is what is known as common code or fall . (Be very careful with this since this trick makes the code less readable).

  • Because switch uses strict comparison it can be used to simplify code when you want to do an identity check.

      

    Two different objects are never equal in both strict and relaxed comparison.

         

    An expression comparing objects is true only if the operands reference exactly the same object.

    Consider the following case

    function fn() {
      // Bloque de código
    }
    
    var arr = [1, 2, 3];
    
    var foo = {};
    
    var obj = {
      prop: fn
    }
    
    switch (obj.prop) {
      case foo:
        console.log('Es el objeto foo');
        break;
      case fn:
        console.log('Es la funcion fn');
        break;
      case arr:
        console.log('Es el arreglo arr');
        break;
      default:
        console.log('No se lo que es');
    }

    switch works with any type of reference, including functions. If you keep a reference to several objects that you want to identify it is very easy to use a switch to know which of them it is because in javascript an object is only equal to itself (an object is not the same as a primitive ).

  • To convert your code to a switch

    var color = "";
    var tipo = prompt("Ingrese un numero");
    
    switch (tipo) {
      case "0":
        color = "FF0000";
        break;
      case "1":
        color = "CC9900";
        break;
      case "2":
        color = "AA0000";
        break;
      default:
        color = "000000";
    }
    alert('El color es: ' + color);
        
    answered by 28.07.2016 в 22:58
    -1

    According to the reference of the W3Schools switch instruction, you can adapt your code as follows:

    var color = "";
    
    switch (color) {
        case "0":
            color = "FF0000";
            break;
        case "1":
            color = "CC9900";
            break;
        case "2":
            color = "AA0000";
            break;
        default:
            // Establece algún valor por defecto 
            // "en caso de que ninguna condición aplique a las opciones anteriores".
            color = "000000";
            break;
    }
    
        
    answered by 28.07.2016 в 22:31