Operators are the marks within an expression that control the way in which the expression's values are evaluated. The operators you use will depend on the ways in which you need to manipulate values. NOTE In this section we review both arithmetic and string operators. For information about logical and comparison operators, see Lesson 8, "Using Conditional Logic." Arithmetic OperatorsEven if you're not very familiar with ActionScript, you'll recognize most of the arithmetic operators. These operators are used in expressions to manipulate numeric values.
String OperatorsUnlike numbers, which can be manipulated using several different operators, strings can be manipulated by only one operator the concatenation operator (they can also be manipulated using various methods of the String class, however). Although other operators work with strings (namely assignment operators and comparison operators), they cannot be used to directly manipulate a string. (For more on comparison operators, see Lesson 8, "Using Conditional Logic.")
PrecedenceExpressions can often include several operators. When this is the case, it's important to understand the order in which parts of the expression are evaluated, or the order of precedence. A value can't be involved in two mathematical operations simultaneously that is, you can't subtract from a value at the same time you're using that value to multiply another number (like the 5 in the expression var myNumber:Number = 20 * 5 - 3; in which one of these evaluations must be completed before the other can begin). Based on the rules of precedence, expressions are evaluated in this order:
Let's take a look at a few examples: var myVariable:Number = 5 + 7 - 3; Because addition and subtraction have the same precedence, this expression is simply evaluated from left to right, with myVariable being assigned a value of 9. var myVariable:Number = 5 + 7 * 3; Because multiplication takes precedence over addition, 7 is multiplied by 3, then 5 is added to that result. In the end, myVariable is assigned a value of 26. var myVariable:Number = (5 + 7) * 3; Because data in parentheses takes precedence, 5 is added to 7, then that result is multiplied by 3. In the end, myVariable is assigned a value of 36. var myVariable:Number = ((2 + 8) * (4 - 2)) / 5; Even though multiplication and division usually take precedence over addition and subtraction, nested parentheses are used to add 2 to 8, then to subtract 2 from 4. These two results are multiplied, then divided by 5. The result is that myVariable is assigned a value of 4. Here is an illustration of this operation: |