Best Way for Conditional Variable Assignment

后端 未结 12 1117
一个人的身影
一个人的身影 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:41

    The first solution uses only one assignment instead of 1,5 by average in the second code snippet. On the other hand the first code snippet is less readable as people not familiar with JavaScript might not realize that the scope of a variable is not block oriented by function oriented - on other languages with C-like syntax myVariable would not be accessible outside if and else blocks.

    In other words both solutions have disadvantages. What about ternary operator:

    var myVariable = condition? 'True' : 'False';
    

    or if you don't care about the camel-case (although I understand this is just an example, not a real code);

    var myVariable = (!!condition).toString();
    

提交回复
热议问题