which would be better if i do this:
if(message == \'redirect\')
{
is_valid.accepted = true;
}
else if(message == \'invalid id\')
{
is_valid.accepted
The switch
statement is more efficient/expressive than if/else
in some cases. While the following if/else
statement
let x = 123;
if (x) {/*...*/} // implicit type casting (to boolean)
else {/*...*/}
can be easily converted to:
switch (!!x) { // explicit type casting (to boolean)
case true: /*...*/ break;
default: /*...*/
}
this switch
statement on the other hand
function algo(x) {/*...performing a complex algorithm...*/}
switch (algo(123)) { // executed once
case "result 1": /*...*/ break;
case "result 2": /*...*/ break;
case "result 3": /*...*/ break;
default: /*...*/
}
results in an incredible inefficient if/else
statement (switch
is more efficient):
if (algo(123) === "result 1") {/*...*/}
else if (algo(123) === "result 2") {/*...*/}
else if (algo(123) === "result 3") {/*...*/}
else {/*...*/}
or requires an if/else
with additional variable, which is declared for this purpose exclusively:
let y = algo(x); // additional variable
if (y === "result 1") {/*...*/}
else if (y === "result 2") {/*...*/}
else if (y === "result 3") {/*...*/}
else {/*...*/}
Please note that additional elements (like variables) cause more complexity and complexity makes programs more error prone. The switch
statement doesn't need such a variable, because it is more expressive.