// 第一种
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? ~
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:
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?
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 .The second type, the second type, the second type, good readability
If it is judged that it does not meet the requirements, return immediately
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: