Reputation: 2092
What I want to do here is use the fewest bytes to call function f
only if the variable a
is not null. The function n
shown will work fine, but according to my web browser, function m
won't work. The browser states:
expected expression, got ';'
I then proceeded to take out the colon, figuring maybe that would do the trick, but I get the error "syntax error".
Is there a way I can shorten function n to a smaller size and have it still work or should I just stick with function n
?
function g(){}
function f(){}
function m(){a?f()g():;}
function n(){if(a){f();g()}}
Upvotes: 2
Views: 73
Reputation: 60597
Code golfing?
Fore!
*ahem*
You could use &&
for the conditional, and +
to call them both together.
function m(){a&&f()+g()}
Note: If by chance f
or g
returns an object, any valueOf
methods will be called, which could have side-effects, but in this context I think that's unlikely.
Upvotes: 3
Reputation: 665545
You can do some tricks with the comma operator:
function m(){a?(f(),g()):…}
and of course the conditional operator always needs a third operand, you cannot just omit it, but use any (short) value:
function m(){a?(f(),g()):0}
You can work around that restriction by using the short-circuit behaviour of the AND operator (see What is "x && foo()"?):
function m(){a&&(f(),g())}
But don't do that. It makes your code totally unreadable.
Should I just stick with function n?
Yes, definitely.
function m() {
if (a) {
f();
g();
}
}
If you want to minify that, use one of the established minifiers instead of hand-optimising it.
Upvotes: 2