Ashton Six
Ashton Six

Reputation: 513

Compact if/else statement [AS3]

Really simple question, I just wanted to know if there was a way to write if/else statements with fewer characters, for example I can create an if statement with either:

if (season == "autumn") {
  tree.gotoAndStop ("brown leaves");
}

or:

if (season == "autumn") tree.gotoAndStop ("brown leaves");

This uses much less space and makes my code look much prettier. With an if/else statement my options seem to be either:

if (season == "autumn" || season == "winter") {
  tree.gotoAndStop ("brown leaves");
} else {
  tree.gotoAndStop ("green leaves");
}

or:

gotoAndStop((season == "autumn" || season == "winter")
            ? "brown leaves" : "green leaves");

Though the second approach isn't always ideal. Do you know any alternatives?

Upvotes: 0

Views: 3248

Answers (1)

zzzzBov
zzzzBov

Reputation: 179284

As far as writing your code in a terse manner, you can use all of the following techniques to manually minify your code, but this is a terrible design decision and will likely lead to headaches and/or bodily harm in the future. Don't say I didn't warn you.

if-else:
if (foo) {
    bar();
} else {
    baz();
}
becomes:
foo?bar():baz()
if:
if (foo) {
    bar();
}
becomes:
foo&&bar();
if-not:
if (!foo) {
    bar();
}
becomes:
foo||bar();
if with multiple statements:
if (foo) {
    bar();
    baz();
    fizz();
    buzz();
}
becomes:
foo&&(bar(),baz(),fizz(),buzz());

Upvotes: 3

Related Questions