Using logical operators

You often use logical operators with comparison operators to determine the condition of an if statement. This is demonstrated by the next example.

To use logical operators in your code:

  1. Select File > New and create a new Flash document.
  2. Open the Actions panel and type the following ActionScript on Frame 1 of the Timeline:
    this.createTextField("myTxt", 20, 0, 0, 100, 20);
    myTxt.type = "input";
    myTxt.border = true;
    myTxt.restrict = "0-9";
    
    this.createEmptyMovieClip("submit_mc", 30);
    submit_mc.beginFill(0xFF0000);
    submit_mc.moveTo(0, 0);
    submit_mc.lineTo(100, 0);
    submit_mc.lineTo(100, 20);
    submit_mc.lineTo(0, 20);
    submit_mc.lineTo(0, 0);
    submit_mc.endFill();
    submit_mc._x = 110;
    
    submit_mc.onRelease = function():Void {
        var myNum:Number = Number(myTxt.text);
        if (isNaN(myNum)) {
            trace("Please enter a number");
            return;
        }
        if ((myNum > 10) && (myNum < 20)) {
            trace("Your number is between 10 and 20");
        } else {
            trace("Your number is NOT between 10 and 20");
        }
    };
    

    In this ActionScript, you create a text field at runtime. If you type a number into the text field and click the button on the Stage, Flash uses the logical operator to display a message in the Output panel. The message depends on the value of the number you type into the text field.

When you use operands, you need to be careful of the order. This is particularly the case when you use complex conditions. In the following snippet, you can see how you use the logical AND operator to check that a number is between 10 and 20. Based on the result, you display an appropriate message. If the number is less than 10 or greater than 20, an alternate message is displayed in the Output panel.

submit_mc.onRelease = function():Void {
    var myNum:Number = Number(myTxt.text);
    if (isNaN(myNum)) {
        trace("Please enter a number");
        return;
    }
    if ((myNum > 10) && (myNum < 20)) {
        trace("Your number is between 10 and 20");
    } else {
        trace("Your number is NOT between 10 and 20");
    }
};