Using numeric operators

You use numeric operators to add, subtract, divide, and multiply values in ActionScript. You can perform different kinds of arithmetic operations. One of the most common operators is the increment operator, commonly formed as i++. There are more things you can do with this operator. For more information on the increment operator, see Using operators to manipulate values.

You can add the increment before (preincrement) or after (postincrement) an operand.

To understand numeric operators in ActionScript:

  1. Create a new Flash document.
  2. Type the following ActionScript into Frame 1 of the Timeline:
    // example one
    var firstScore:Number = 29;
    if (++firstScore >= 30) {
        // should trace
        trace("Success! ++firstScore is >= 30");
    }
    // example two
    var secondScore:Number = 29;
    if (secondScore++ >= 30) {
        // shouldn't trace
        trace("Success! secondScore++ is >= 30");
    }
    
  3. Select Control > Test Movie to test the ActionScript

    The "Example one" code block traces, but the "Example two" code block does not. The first example uses a preincrement (++firstScore) to increment and calculate firstScore before it's tested against 30. Therefore, firstScore increments to 30 and then tests against 30.

    However, Example two uses a postincrement (secondScore++), which evaluates after the test is performed. Therefore, 29 compares against 30, and then increments to 30 after the evaluation.

When you work with the addition operator, you can have unexpected results if you try to add values in an expression, as you can see in the following example:

trace("the sum of 5 + 2 is: " + 5 + 2); // the sum of 5 + 2 is: 52

Flash concatenates the values 5 and 2 instead of adding them. To work around this, you can wrap the expression 5+2 in a pair of parentheses, as shown in the following code:

trace("the sum of 5 + 2 is: " + (5 + 2)); // the sum of 5 + 2 is: 7

For more information on operator precedence, see About operator precedence and associativity.

When you load data from external sources (such as XML files, FlashVars, web services, and so on), you need to be very careful when you work with numeric operators. Sometimes Flash treats the numbers like strings because the SWF file isn't aware of the number's data type. In this case, you could add 3 and 7 with a result of 37 because both numbers are concatenated like strings instead of adding numerically. In this situation, you need to manually convert the data from strings to numbers using the Number() function.