admin管理员组文章数量:1310193
So I know
variable && runTrue();
really means
if(variable){
runTrue();
}
Then is there a more simplified way to write
if(variable){
runTrue();
}else{
runFalse();
}
instead of if-else
?
So I know
variable && runTrue();
really means
if(variable){
runTrue();
}
Then is there a more simplified way to write
if(variable){
runTrue();
}else{
runFalse();
}
instead of if-else
?
- 2 Have you thought perhaps that you might want to write your code in such a way that people can actually read it, without having to think too much? – paxdiablo Commented May 31, 2012 at 2:33
- To a sufficiently experienced coder, the most "simplified" code is the easiest code to read. If you want to make your JavaScript code more pact, then write readable code first, and then run it through a pressor (Uglify or something similar) as part of your deployment process. Win-win: you get to maintain code that you can read, but the end result is a smaller download for your users. – Joe White Commented May 31, 2012 at 2:46
2 Answers
Reset to default 7Ternary expressions using the conditional operator ? :
were invented for such simple binary choices:
function a() {alert('odd')}
function b() {alert('even')}
var foo = new Date() % 2;
foo? a() : b(); // odd or even, more or less randomly
is equivalent to:
if (foo % 2) {
a(); // foo is odd
} else {
b(); // foo is even
}
Yes, I found out that this would do the same thing as a normal if-else
:
(variable) && (runTrue(),1) || runFalse();
It is 2 characters shorter (still better than nothing) and tested in jsPerf that usually Short-circut evaluation - false
for most of time is faster than the normal way of doing this.
(variable) && //If variable is true, then execute runTrue and return 1
(runTrue(),1) || // (so that it wouldn't execute runFalse)
runFalse(); //If variable is false, then runFalse will be executed.
But of course, you can always use variable?runTrue():runFalse();
.
本文标签: javascriptShortcircuit for Ifelse statementStack Overflow
版权声明:本文标题:javascript - Short-circuit for If-else statement - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741836625a2400254.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论