javascript - if determines whether to use else statement or return to execute another condition
学习ing
学习ing 2017-06-12 09:31:02
0
6
934
// 第一种
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? ~

学习ing
学习ing

reply all(6)
女神的闺蜜爱上我

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.

学霸

What if it’s inside a function?

学习ing

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 else
The 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;
}
//...
//满足合格条件
我想大声告诉你

The second type, the second type, the second type, good readability
If it is judged that it does not meet the requirements, return immediately

Peter_Zhu

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.

伊谢尔伦

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]();
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!