Best Way for Conditional Variable Assignment

后端 未结 12 1110
一个人的身影
一个人的身影 2021-01-31 02:26

Which is the better way for conditional variable assignment?

1st method

 if (true) {
   var myVariable = \'True\';
 } else {
   var myVariable = \'False\         


        
12条回答
  •  情歌与酒
    2021-01-31 02:58

    Just for completion, there is another way in addition to all the others mentioned here, which is to use a lookup table.

    Say you have many possible values, you could declaratively configure a Map instead of using an if, switch or ternary statement.

    Object map = {
       key1: 'value1',
       key2: 'value2,
       keyX: 'valueX'
    };
    
    var myVariable = map[myInput];
    

    This works even for booleans:

    Object map = { true: 'value1', false: 'value2 };
    
    var myVariable = map[myBoolean];
    

    For booleans you would probably do it the 'normal' way though with logic operators specifically designed for that. Though sometimes it can be useful, such as:

    • portability: you can pass a map around
    • configurability: maybe the values come from a property file
    • readability: if you don't care it's a boolean or not, you just want to avoid conditional logic and reduce cognitive load that way

    Note there is some overlap between the advantages using a lookup map and advantages of using a function variable (closure).

提交回复
热议问题