User Guide
78 ActionScript Language and Syntax
Some operators are overloaded, which means that they behave differently depending on the
type or quantity of operands passed to them. The addition (
+) operator is an example of an
overloaded operator that behaves differently depending on the data type of the operands. If
both operands are numbers, the addition operator returns the sum of the values. If both
operands are strings, the addition operator returns the concatenation of the two operands.
The following example code shows how the operator behaves differently depending on the
operands.
trace(5 + 5); // 10
trace("5" + "5"); // 55
Operators can also behave differently based on the number of operands supplied. The
subtraction (
-) operator is both a unary and binary operator. When supplied with only one
operand, the subtraction operator negates the operand and returns the result. When supplied
with two operands, the subtraction operator returns the difference between the operands. The
following example shows the subtraction operator used first as a unary operator, and then as a
binary operator.
trace(-3); // -3
trace(7-2); // 5
Operator precedence and associativity
Operator precedence and associativity determine the order in which operators are processed.
Although it may seem natural to those familiar with arithmetic that the compiler processes the
multiplication (
*) operator before the addition (+) operator, the compiler needs explicit
instructions about which operators to process first. Such instructions are collectively referred
to as operator precedence. ActionScript defines a default operator precedence that you can alter
using the parentheses (
()) operator. For example, the following code alters the default
precedence in the previous example to force the compiler to process the addition operator
before the multiplication operator:
var sumNumber:uint = (2 + 3) * 4; // uint == 20
You may encounter situations in which two or more operators of the same precedence appear
in the same expression. In these cases, the compiler uses the rules of associativity to determine
which operator to process first. All of the binary operators, except the assignment operators,
are left-associative, which means that operators on the left are processed before operators on
the right. The assignment operators and the conditional (
?:) operator are right-associative,
which means that the operators on the right are processed before operators on the left.