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