Вопрос

var foo = true;

function doThis() {alert("do this");}
function doThat() {alert("do that");}

// fine
if(foo) {
    doThis();
    doThat();
}

// fine
foo && (doThis());

// NO, syntax error
foo && (doThis(); doThat(););

Is this even possible? Or I should'v not done this at all?

Это было полезно?

Решение

Yes, if you separate the functions with commas:

foo && (bar(), baz())

This is a terrible coding practice, but it's useful for minifying code, or the purposes of code golf.

if (foo) {
    bar();
    baz();
}

turns into:

foo&&(bar(),baz())

and

if (!foo) {
    bar();
    baz();
}

turns into:

foo||(bar(),baz())

and

if (foo) {
    bar();
    baz();
} else {
    fizz();
    buzz();
}

turns into:

foo?(bar(),baz()):(fizz(),buzz())

although the variables would likely be renamed in a minifier to something like:

a&&(b(),c())

Другие советы

You can't put a semicolon in the middle of an expression.

foo && (doThis() || doThat());

As doThis has no return value, it evaluates as follows:

true && (doThis() || doThat());
(doThis() || doThat());
(undefined || doThat());
(doThat());
undefined;

But as answered by @zzzzBov, the comma operator can also be used and it is better in the sense that it doesn't depend on return values.

Note that such shorthands are not very readable, you should let minification tools do that kind of work. (e.g. Closure Compiler)

You can use the comma operator:

foo && (doThis(), doThat());

Of course if doThis returns a truthy value you can also have:

foo && doThis() && doThat();

But it's more like;

if (foo)
    if (doThis())
        doThat();

However usually this "shorthand" are not used if there is no assignment on the left, because makes the code uglier and less readable.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top