If Else in ActionScript

Branching with if and else in ActionScript is straightforward.

package {
    import flash.display.Sprite;
    import flash.text.TextField;

    public class IfElseExample extends Sprite {
        public function IfElseExample() {
            // Here's a basic example.
            if (7 % 2 == 0) {
                trace("7 is even");
            } else {
                trace("7 is odd");
            }

            // You can have an if statement without an else.
            if (8 % 4 == 0) {
                trace("8 is divisible by 4");
            }

            // Logical operators like && and || are often useful in conditions.
            if (8 % 2 == 0 || 7 % 2 == 0) {
                trace("either 8 or 7 are even");
            }

            // A variable can be declared and initialized before the condition.
            // This variable will be available in the current and all subsequent branches.
            var num:int = 9;
            if (num < 0) {
                trace(num + " is negative");
            } else if (num < 10) {
                trace(num + " has 1 digit");
            } else {
                trace(num + " has multiple digits");
            }
        }
    }
}

To run this ActionScript program, you would typically compile it into a SWF file and then run it in a Flash player or browser. The output would be:

7 is odd
8 is divisible by 4
either 8 or 7 are even
9 has 1 digit

Note that in ActionScript, you need parentheses around conditions, and braces are required for multi-line blocks. ActionScript also uses the trace function for console output, which is similar to println in other languages.

ActionScript doesn’t have a ternary operator like some other languages, so you’ll need to use a full if statement even for basic conditions.


Next example: Switch statements in ActionScript.