ActionScript 3 fundamentals: Operators


 

Requirements
   
Prerequisite knowledge Required products  
You should be familiar with ActionScript 3 syntax, data types, and variables.

 

User level
Beginning
Flash Builder (Download trial)
 
 
Operators are the core component of any logic that exists in your application. They instruct the Flash Player to perform a variety of operations, including comparing two values, adding numbers, combining multiple strings together or even manipulating low-level binary data.
 
In this article, you will learn the types of operators provided by Flash Player. You will also learn how each is intended to be used and the order in which they are applied when used in conjunction.

Operators and operands

 

Operators are special symbols (or occasionally words) that are used to perform calculations and to compare, modify, or combine values of variables, objects, properties, and expressions. They take one or more operands and frequently return a value.
 
An operand is a value—a literal, a variable, or an expression—that an operator uses as input. For example, in the following code, the addition (+) and multiplication (*) operators are used with three literal operands (2, 3, and 4) to return a value. The assignment (=) operator then assigns the returned value, 14, to the variable sumNumber.
 
var sumNumber:uint = 2 + 3 * 4; // sumNumber is now 14
 
Prefix operators come before their operand. Logical NOT (!) and negation (-) are examples of prefix operators. Postfix operators come after their operands. Increment (++) and decrement (--) are examples of postfix operators. Interfix operators come between operands. In 2 * y
, the multiplication operator is an interfix operator.
 
Operators can be unary, binary, or ternary. A unary operator, such as the increment operator (++), takes one operand. A binary operator, like the division operator (/), takes two operands. A ternary operator takes three operands. It is important to provide the correct number of operands.
 
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(“Hello” + “world”); // Helloworld trace("5" + "5"); // 55

Types of operators

 

Arithmetic operators

The additive and multiplicative operators (+,-,*,/) take two operands and perform the appropriate calculation. The modulo operator returns the remainder after a division operation. Increment (++) and decrement (--) are unary operators and therefore only require one operand. They either add (increment) or subtract (decrement) 1 from the expression they are used on. They can be used as either prefix or postfix operators.
 
Table 1. Arithmetic operators
 
Operator
Operation performed
+
Addition: Adds numeric expressions
-
Subtraction : Negates or subtracts numeric expressions
*
Multiplication : Multiplies two numerical expressions
/
Division : Divides expression1 by expression2
%
Modulo: Calculates the remainder of expression1 divided by expression2
++
Increment : Adds 1 to a numeric expression
--
Decrement : Subtracts 1 from a numeric expression
 
The increment (++) and decrement (--) operators can be used as prefix or postfix operators. When used as prefix operators, the increment or decrement operation is completed before the value of the overall expression is returned. For example, the following code shows how the value of the expression ++xNum is returned after the value is incremented:
 

var xNum:Number = 0;

trace(++xNum); // 1

trace(xNum); // 1

 

When increment or decrement is used as a postfix operator, the expression's value is returned before the postfix operator is processed. For example, the following code shows how the value of the expression xNum++ is returned before the value is incremented:
 
var xNum:Number = 0; trace(xNum++); // 0 trace(xNum); // 1

 

Assignment and compound assignment operators

The assignment operator assigns the value of the expression on the right to the operand on the left. The operand on the right can be any expression that ActionScript 3 can evaluate. The operand on the left must be a single variable, array element, or property.
 
Compound assignment operators perform arithmetic on a variable and then store the result in that same variable.
 
Table 2. Assignment and compound assignment operators
 
Operator
Operation performed
Example

 

=

 

Assignment : Assigns the value of expression2 (the operand on the right) to the variable, array element, or property in expression1 (the operand on the left)

 

 

var x:uint = 10; // x is now 10
                 // var y:uint = (5+7)/2;
                 // y is now 6
                 // var text:String = "Hello";
                 // text is now Hello

 

+=

Addition assignment : Assigns expression1 the value of expression1 + expression2

var x:uint = 5; x += 5; // x is now 10

-=

Subtraction assignment : Assigns expression1 the value of expression1 - expression2

var x:uint = 5; x -= 5; // x is now 0

*=

Multiplication assignment : Assigns expression1 the value of expression1 * expression2

var x:uint = 5; x *= 5; // x is now 25

/=

Division assignment : Assigns expression1 the value of expression1 / expression2

var x:uint = 5; x /= 5; // x is now 1

%=

Modulo assignment : Assigns expression1 the value of expression1 % expression2

var x:uint = 13; x %= 5; // x is now 3

 

Equality and comparison operators

The equality operators take two operands, compare their values, and return a Boolean value. The relational operators take two operands, compare their values, and return a Boolean value.

 

Table 3. Equality and comparison operators
 
Operator
Operation performed
Example

==

Equality : Tests two expressions for equality. The result is true if the expressions are equal.

var a:uint = 13;
var b:uint = 13;
trace(a==b); // true
var c:String = "Hello";
var d:String = "World";
trace(c==d); // false

!=

Inequality : Tests for the exact opposite of the equality ( == ) operator. If expression1 is equal to expression2 , the result is false.

var a:uint = 13;
var b:uint = 13;
trace(a!=b); // false
var c:String = "Hello";
var d:String = "World";
trace(c==d); // true

===

Strict equality : Tests two expressions for equality, but does not perform automatic data conversion. The result is true if both expressions, including their data types, are equal.

var a:uint = 13;
var b:Number = 13;
trace(a===b); // false
var c:uint = 22;
var d:uint = 22;
trace(c===d); // true

!==

Strict inequality : Tests for the exact opposite of the strict equality ( === ) operator. If expression1 is equal to expression2 , and their data types are equal, the result is false.

var a:uint = 13;
var b:Number = 13;
trace(a!==b); // true
var c:uint = 22;
var d:uint = 22;
trace(c!==d); // false

<

Less than : Compares two expressions and determines whether expression1 is less than expression2 ; if it is, the result is true.

var x:int = 27;
var y:int = 42;
var z:int = 101;
trace(x<y); // true
trace(z<y); // false

>

Greater than : Compares two expressions and determines whether expression1 is greater than expression2 ; if it is, the result is true.

var x:int = 27;
var y:int = 42;
var z:int = 101;
trace(x>y); // false
trace(z>y); // true

<=

Less than or equal to : Compares two expressions and determines whether expression1 is less than or equal to expression2 ; if it is, the result is true.

var x:int = 27;
var y:int = 42;
var z:int = 42;
trace(x<=y); // true
trace(y<=z); // true

>=

Greater than or equal to : Compares two expressions and determines whether expression1 is greater than or equal to expression2 ; if it is, the result is true.

var x:int = 27;
var y:int = 42;
var z:int = 42;
trace(x>=y); // false
trace(y>=z); // true

 

Logical operators

The logical operators take two operands and return a Boolean result. They are frequently used to combine conditions.
 
Table 4. Logical operators

 

Operator
Operation performed

!

Logical NOT : Inverts the Boolean value of a variable or expression

&&

Logical AND : Returns expression1 if it is false or can be converted to false , and expression2 otherwise. If both operands are of type Boolean, the result is true only if both operands are true

||

Logical OR : Returns expression1 if it is true or can be converted to true, and expression2 otherwise. If both operands are of type Boolean, the result is true if either or both expressions are true; the result is false only if both expressions are false.

&&=

Logical AND assignment : Assigns expression1 the value of expression1 && expression2

||=

Logical OR assignment : Assigns expression1 the value of expression1 || expression2

 

Bitwise logical operators

The bitwise logical operators take two operands and perform bit-level logical operations.
 
Table 5. Bitwise logical operators

 

Operator
Operation performed

~

Bitwise NOT : Converts expression to a 32-bit signed integer, and then applies a bitwise one's complement

&

Bitwise AND : Converts expression1 and expression2 to 32-bit unsigned integers, and performs a Boolean AND operation on each bit of the integer parameters

|

Bitwise OR : Returns expression1 if it is true or can be converted to true, and expression2 otherwise. If both operands are of type Boolean, the result is true if either or both expressions are true; the result is false only if both expressions are false.

^

Bitwise XOR : Converts expression1 and expression2 to 32-bit unsigned integers, and places a 1 in each bit position where the corresponding bits in expression1 or expression2 , but not both, are 1

&=

Bitwise AND assignment : Assigns expression1 the value of expression1 & expression2

|=

Bitwise OR assignment : Assigns expression1 the value of expression1 | expression2

^=

Bitwise XOR assignment : Assigns expression1 the value of expression1 ^ expression2

 

Bitwise shift operators

The bitwise shift operators take two operands and shift the bits of the first operand to the extent specified by the second operand.

 

Table 6. Bitwise shift operators

 

Operator
Operation performed

<<

Bitwise left shift : Converts expression1 and shiftCount to 32-bit integers, and shifts all the bits in expression1 to the left by the number of places specified by the integer resulting from the conversion of shiftCount

>>

Bitwise right shift : Converts expression1 and shiftCount to 32-bit integers, and shifts all the bits in expression to the right by the number of places specified by the integer that results from the conversion of shiftCount

>>>

Bitwise unsigned right shift : The same as the bitwise right shift ( >> ) operator except that it does not preserve the sign of the original expression because the bits on the left are always filled with 0

<<=

Bitwise left shift assignment : Performs a bitwise left shift operation and stores the contents as a result in expression1

>>=

Bitwise right shift assignment : Performs a bitwise right shift operation and stores the contents as a result in expression1

>>>=

Bitwise unsigned right shift assignment : Performs an unsigned bitwise right-shift operation and stores the result in expression1

 

Other operators

The primary operators include those operators used for creating Array and Object literals, grouping expressions, calling functions, instantiating class instances, and accessing properties.
The conditional operator is a ternary operator, which means that it takes three operands. The conditional operator is a shorthand method of applying the
if..else conditional statement.
 
Table 7. Other operators

 

Operator
Operation performed

[]

Array access : Initializes a new array or accesses elements in an array

as

as : Evaluates whether an expression specified by the first operand is a member of the data type specified by the second operand

?:

Conditional : Evaluates expression1 , and if the value of expression1 is true , the result is the value of expression2 ; otherwise the result is the value of expression3

delete

delete : Destroys the object property specified by reference; the result is true if the property does not exist after the operation completes, and false otherwise

.

Dot : Accesses class variables and methods, gets and sets object properties, and delimits imported packages or classes

in

in : Evaluates whether a property is part of a specific object

instanceof

instanceof : Evaluates whether an expression's prototype chain includes the prototype object for function

is

is : Evaluates whether an object is compatible with a specific data type, class, or interface

::

Name qualifier : Identifies the namespace of a property, a method, an XML property, or an XML attribute

new

new : Instantiates a class instance

{x:y}

Object initializer : Creates an object and initializes it with the specified name and value property pairs

()

Parentheses : Performs a grouping operation on one or more parameters, performs sequential evaluation of expressions, or surrounds one or more parameters and passes them as arguments to a function that precedes the parentheses

/

RegExp delimiter : When used before and after characters, indicates that the characters have a literal value and are considered a regular expression (RegExp), not a variable, string, or other ActionScript element.

:

Type : Used for assigning a data type; this operator specifies the variable type, function return type, or function parameter type

typeof

typeof : Evaluates expression and returns a string specifying the expression's data type

void

void : Evaluates an expression and then discards its value, returning undefined

Operator precedence and associativity

 

Operator precedence and associativity determine the order in which operators are processed. The compiler needs explicit instructions about which operators to process first. Such instructions are collectively referred to as operator precedence. Higher precedence operators are processed before lower precedence operators. The order of operations of arithmetic is maintained within the default operator precedence of ActionScript 3. You can alter the default precedence 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; // sumNumber is 20

 

If two or more operators of the same precedence appear in the same expression, 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.
 
For example, consider the less-than (<) and greater-than (>) operators, which have the same precedence. If both operators are used in the same expression, the operator on the left is processed first because both operators are left-associative. This means that the following two statements produce the same output:
 
trace(3 > 2 < 1); // false trace((3 > 2) < 1); // false
 
The greater-than operator is processed first, which results in a value of true, because the operand 3 is greater than the operand 2. The value true is then passed to the less-than operator along with the operand 1. The following code represents this intermediate state:

 

trace((true) < 1);

 

The less-than operator converts the value true to the numeric value 1 and compares that numeric value to the second operand 1 to return the value false.

 

trace(1 < 1); // false
You can alter the default left associativity with the parentheses operator. You can instruct the compiler to process the less-than operator first by enclosing that operator and its operands in parentheses. The following example uses the parentheses operator to produce a different output using the same numbers as the previous example:
 
trace(3 > (2 < 1)); // true

 

The less-than operator is processed first, which results in a value of false
because the operand 2 is not less than the operand 1. The value false
is then passed to the greater-than operator along with the operand 3. The following code represents this intermediate state:
 
trace(3 > (false));

 

The greater-than operator converts the value false to the numeric value 0 and compares that numeric value to the other operand 3 to return true.
 
trace(3 > 0); // true

 

The following table lists the operators for ActionScript 3 in order of decreasing precedence. Each row of the table contains operators of the same precedence. Each row of operators has higher precedence than the row appearing below it in the table.
 
Table 8. Operator precedence and associativity

 

Group
Operators
Primary

[] {x:y} () f(x) new x.y x[y] <></> @ :: ..

Postfix

x++ x--

Unary

++x --x + - ~ ! delete typeof void

Multiplicative

* / %

Additive

+ -

Bitwise shift

<< >> >>>

Relational

< > <= >= as in instanceof is

Equality

== != === !==

Bitwise AND

&

Bitwise XOR

^

Bitwise OR

|

Logical AND

&&

Logical OR

||

Conditional

?:

Assignment

= *= /= %= += -= <<= >>= >>>= &= ^= |=

Comma

,

Where to go from here

 
The operators presented in this article are fundamental to ActionScript 3. They are the engine which provides functionality and controls the flow of your application.
 
Each operator works on specific types of data and provide capabilities which are expanded upon to create function and methods. For more information on functions read ActionScript 3 fundamentals: Functions. Learn about objects and classes in ActionScript 3 by reading Introduction to objects, Introduction to Classes, and Writing classes in ActionScript 3 (all coming October 31).

    Acknowledgement

 
The content in this article is based on material originally published in the Learning ActionScript 3 user guide created by Adobe Community Help and Learning.