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);