// 第一种
if (test) {
console.log('Yes~');
} else {
console.log('No~');
}
// 第二种
if (test) {
console.log('Yes~');
return;
}
console.log('No~');
Which one is better? The second one looks clearer, with less indentation, but one more character than the first one. In terms of performance, which one is better? ~
女神的闺蜜爱上我2017-06-12 09:33:02
The first one is very ugly and verbose. .
Secondly, generally speaking, the judgment should be made as early as possible in the function so that return
can be used to exit the function
, so the second method is generally better.
You can change it to the following:
if (test) return console.log('Yes~')
console.log('No~')
if (test) console.log('Yes~')
else console.log('No~')
test?(console.log('Yes~')):(console.log('No~'))
Of course you have to weigh it against readability and simple elegance, this is more a matter of personal style.
学习ing2017-06-12 09:33:02
This is not a performance issue. When you have many judgment conditions, the advantage of the second type is very obvious, unless you are willing to write a lot of elseThe judgment statement should end as soon as possible
. In actual situations, it is usually multiple unqualified conditions + one qualified condition .
if(满足不合格条件1) {
return;
}
if(满足不合格条件2) {
return;
}
//...
//满足合格条件
我想大声告诉你2017-06-12 09:33:02
The second type, the second type, the second type, good readability
If it is judged that it does not meet the requirements, return immediately
天蓬老师2017-06-12 09:33:02
I personally like the second one. Once the logic ends, it returns directly and is clear and organized.
The first one is as simple as it is. If it is complicated, you need to read a lot of code to find the returned result.
伊谢尔伦2017-06-12 09:33:02
The second method, to some extent, the process is clearer (telling you what can be done and what cannot be done).
But it’s better when you don’t need if...else. For example:
var ofn = {
yes : function(){ console.log('yes'); },
no : function(){ console.log('no'); },
};
var key = test ? "yes" : "no";
ofn[key]();