javascript switch() or if()

前端 未结 6 1362
孤独总比滥情好
孤独总比滥情好 2020-12-11 11:37

which would be better if i do this:

if(message == \'redirect\')
{
    is_valid.accepted = true;
}
else if(message == \'invalid id\')
{
    is_valid.accepted          


        
6条回答
  •  温柔的废话
    2020-12-11 12:22

    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.

提交回复
热议问题