Best Way for Conditional Variable Assignment

2020-05-15 14:52发布

Which is the better way for conditional variable assignment?

1st method

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

2nd Method

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

I actually prefer 2nd one without any specific technical reason. What do you guys think?

标签: javascript
12条回答
霸刀☆藐视天下
2楼-- · 2020-05-15 15:33

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();
查看更多
我想做一个坏孩纸
3楼-- · 2020-05-15 15:37

try this

var myVariable = (true condition) ? "true" : "false"
查看更多
We Are One
4楼-- · 2020-05-15 15:38

Another cool thing is that you can do multiple assignment based on a conditional:

let [long_str, short_str] = a.length > b.length ? [a, b] : [b, a]
查看更多
戒情不戒烟
5楼-- · 2020-05-15 15:41

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

查看更多
一纸荒年 Trace。
6楼-- · 2020-05-15 15:42

You could do a ternary, which is a lot shorter (and no darn curly braces):

var myVariable = (true) ? 'True' : 'False';
查看更多
爱情/是我丢掉的垃圾
7楼-- · 2020-05-15 15:44

I would prefer 2nd option too, no technical reason but for the sake of easy to read code, readability is very important in code.

If you see the second option, from processing point of view only one check will ever be executed, saved some very minute processing time, so there is only one check in second case.

查看更多
登录 后发表回答