Introduction to ActionScript 2.0/Operators
Key concepts:
- Operators
- Operator types
- Arithmetic operators
- Text concatenation operator
- Comparison operators
- Different types of comparison
- Logical operators
- Assignment operators
- Two types of simple assignment
- Compound assignment operators
- Incremental and decremental operators
- Operator precedence
- Operator associativity
- Comments
- Expressions vs. statements
An operator is something, usually a sign like + or -, that is used to manipulate different entities. The entities manipulated are called operands. If you have experience with programming, SQL or even simple computer languages like spreadsheet formulae, you should be familiar with a lot of them already. In the last chapter, we have already introduced the assignment operator. In this chapter, we will go into detail about the most useful operators. (Note: dot and array access operators are also useful, but we'll save that till later when we learn about properties and methods.)
What are the most useful operators?
editArithmetic operators
editAn arithmetic operator is an operator that does maths for you. The four basic arithmetic operators are as follows:
- + does addition.
- - does subtraction.
- * does multiplication.
- / does division.
Now, you may be tempted to write such a code:
Code | Result |
---|---|
1 + 1;
|
|
However, this will give you an error. This is because 1 + 1 is only an expression with a value of 2; it is not a statement. (Recall: statements tell the computer to do something.) Therefore, we should write this instead:
Code | Result |
---|---|
trace(1 + 1);
|
|
Again, just take the 'trace' thing for granted for now. Enter this into the ActionScript of the first frame and preview your Flash file. '2' should appear on the output box.
In addition to the above, a less frequently used operator, %, can calculate the remainder of a division operation. 10 % 3, for example, returns 1. Other operations (such as exponents, square roots, etc.) cannot be evaluated using operators and we'll learn them later.
Text concatenation operator
editOne peculiarity of Flash is that + acts as both the addition operator and the text concatenation operator. The text concatenation operator turns two strings into one. For example, by concatenating "This is" and " Sparta" (note the space before Sparta), we'll get "This is Sparta". If we concatenate "This is" and "Sparta", however, we'll get "This isSparta", which is undesirable.
If the entites on either side of the + sign are both numbers, the + will act as the addition operator. Otherwise, the + will act as a text concatenation operator. Here's an example:
Code | Result |
---|---|
trace(1 + 1);
trace("1" + 1);
trace(1 + "1");
trace("1" + "1");
|
|
Comparison operators
editComparison operators are operators which compare two entities and return a Boolean value.
Equality operator
editThe equality operator (==) compares two entites and determines whether they are exactly the same. If it's the same, it returns true
; otherwise, it returns false
. Here's some sample code:
Code | Result |
---|---|
trace(1 == 2);
trace(1 == 1);
trace("Hello world" == "Hello world");
trace("This is sparta!" == "This is Sparta!");
|
|
Note that the last one is false because the equality operator is case-sensitive.
When we're working with composite data types, we need to be more careful. The equality operator will only return true
if they are referring to the same entity. Even if we have two distinct identical entities, the equality operator will return false
. In this example, let's imagine there are two dogs. One is called Spot, and it has another name, Bandian (which is Chinese for 'spot'). The other is called 'Lucky' and they are twins, and are physiologically the same in every way.
Code | Result |
---|---|
trace(spot == bandian);
trace(spot == lucky);
|
|
Sometimes, we compare two entities of different data types, such as 23 and "23". In this case, the equality operator will still return true
by automatically converting "23" to 23 for you. If you don't want this automatic conversion, use the strict equality operator (===).
Code | Result |
---|---|
trace(23 == "23");
trace(23 === "23");
|
|
Inequality operators
editFlash provides several inequality operators for all your comparing needs.
The first operator is !=. != does the opposite of ==: if the two are equal, it returns false
, and if the two are unequal, it returns true. Consider the following code:
Code | Result |
---|---|
trace(1 != 2);
trace("2" != 2);
|
|
You've probably noticed that != also converts the data types where necessary. If you don't want that to happen, use !==.
Code | Result |
---|---|
trace("2" !== 2);
|
|
The other four operators are <, >, <= and >=. They do the same as <, >, ≤ and ≥ in mathematics. If you need a quick refresher, here you go:
- < means 'smaller than'.
- > means 'larger than'.
- <= means 'smaller than or equal to'.
- >= means 'larger than or equal to'.
Look at the following example:
Code | Result |
---|---|
trace(12 < 3);
trace(12 > 3);
trace(12 <= 3);
trace(12 >= 3);
trace(12 < 12);
trace(12 > 12);
trace(12 <= 12);
trace(12 >= 12);
|
|
We can also compare strings. No, really! The strings are converted into their Unicode code points in order to be compared. See Unicode/Character reference/0000-0FFF for the code points.
Code | Result |
---|---|
trace("Apple" > "Ball");
trace("Apple" < "Ball");
trace("apple" < "Ball");
trace("apple" != "apple");
|
|
With letters of the same case, later letters have larger values than earlier letters, so a < b and A < B. However, uppercase letters are always smaller than lowercase letters, so a > B.
Logical operators
editLike most languages, the most important logical operators are AND, OR and NOT.
&& is ActionScript's AND operator. Its operands must be Boolean. If both operands are true
, it returns true
; otherwise, it returns false
.
Code | Result |
---|---|
trace(true && false);
trace(false && false);
trace(true && true);
trace(1>0 && 1=1);
trace(1<0 && 1=1);
|
|
|| is ActionScript's OR operator. Its operands must be Boolean. If neither operand is true
, it returns false
; otherwise, it returns true
.
Code | Result |
---|---|
trace(true || false);
trace(false || false);
trace(true || true);
trace(1>0 || 1=1);
trace(1<0 || 1=1);
|
|
Note that there must be two ampersands for AND and two vertical bars for OR.[1]
! (pronounced 'bang') is ActionScript's NOT operator. It is added before the operand.It flips Boolean variables around: false
becomes true
and true
becomes false
.
Code | Result |
---|---|
trace(!false);
trace(!true);
trace(!true && true);
trace(!false && true);
|
|
Assignment operators
editSimple assignment operator
editWe've already met the simple assignment operator in the last chapter, but there's something else we need to clarify first. The simple assignment operator actually does two distinct things:
- With primitive data types, the assignment operator simply copies the assigned value to the variable.
- With other data types, the assignment operator puts a link to the assigned entity inside the variable!
What does this mean?
Code | Result |
---|---|
var string_1:String = "Wikibooks";
var string_2:String = string_1;
string_2 = "Wikipedia";
trace(string_1);
|
|
Here, Flash copied the value "Wikibooks" to string_2. After we changed string_2 to "Wikipedia", the original string_1 is not affected. Consider another situation with a non-primitive data type, Dog:
Code | Result |
---|---|
//Assume that spot is a chihuahua.
var nicestDog:Dog = spot;
nicestDog.species = "pekingese";
|
|
The first line is a comment; we'll talk about that at the end of the chapter. You don't have to understand the third line, either; just assume that it changes the species of nicestDog to 'pekingese'. Now, do you think changing nicestDog's species to 'pekingese' will genetically alter Spot, a chihuahua, into a pekingese? The answer is yes. This is because nicestDog only contains a link to spot.
Compound assignment operators
editThere are two types of compound assignment operators. We will only talk about the type that combines assignment and arithmetic operators. If you're interested, you can check the official Flash documentation to learn about the other type.
Compound assignment operators always work with numbers. There are five of them, each corresponding to one arithmetic operator:
- +=, the addition and reassignment operator
- -=, the subtraction and reassignment operator
- *=, the multiplication and reassignment operator
- /=, the division and reassignment operator
- %=, the modulus and reassignment operator
What these operators do is to perform an operation on the left operand and the right operand, then assign the value to the left operand. In other words,
a += b;
is equivalent to
a = a + b;
Let's better = understand this concept with an example.
Code | Result |
---|---|
var number_1:Number = 5;
number_1 *= 2;
trace(number_1);
|
|
In this example, Flash multiplied number_1 with 5, then assigned the value to number_1.
What do assignment operators return?
editSo far, we've seen that arithmetic operators, logical operators, comparison operators and and the text concatenation operator all return a value. Since assignment operators can be statements per se, does that mean they do not return a value?
In fact, assignment operators do return values. The value returned by an assignment operator is the value assigned to the left operand. For example, a = 2
returns the value 2, while a /= 2
returns half the original value of a.
The following code may look counter-intuitive, but it works:
Code | Result |
---|---|
var a = 6;
var some_number:Number = 3 + (a += 1);
trace(some_number);
trace(a);
|
|
Here, a += 1
returns 7. The round brackets are to allow the operation inside it to be performed first; we'll discuss that later.
Incremental operators
editActionScript offers four incremental/decremental operators:
- The postfix increment operator, written as
variableName++
- The prefix increment operator, written as
++variableName
- The postfix decrement operator, written as
variableName--
- The prefix decrement operator, written as
--variableName
Both incremental operators add 1 to integral variables, and both decremental operators subtract 1 from integral variables. They are statements in their own rights. For example:
Code | Result |
---|---|
var myFirstNumber:Number = 10;
myFirstNumber++;
trace(myFirstNumber);
myFirstNumber--;
trace(myFirstNumber);
++myFirstNumber;
trace(myFirstNumber);
--myFirstNumber;
trace(myFirstNumber);
|
|
As you can see, incremental and decremental operators when the are statements per se. However, we sometimes want to place the incremental operator into another statement. With the postfix increment/decrement operators, everything else will be evaluated before going back to the increment/decrement. With the prefix increment/decrement operators, the increment/decrement will be evaluated before everything else.
If that sounds confusing, look at the following examples:
Code | Result |
---|---|
var myFirstNumber:Number = 10;
trace(myFirstNumber++);
trace(myFirstNumber);
|
|
Code | Result |
---|---|
var myFirstNumber:Number = 10;
trace(++myFirstNumber);
trace(myFirstNumber);
|
|
In our first example, myFirstNumber
was traced before the increment operation. That's why we still see 10 in the first trace statement. The second trace statement displays the computed value 11.
In our second example, myFirstNumber
was traced after the increment operation, so we can already see the 11 in the first trace.
What is the order of operations?
editRemember the order of operations (PEMDAS or BOMDAS/BIMDAS) you learnt in Maths class? ActionScript also applies different operators in a fixed order.
In ActionScript, there are two things we need to consider when determining the order of operations: operator precedence and operator associativity.
What is operator precedence?
editWhen one operator is always evaluated before the other, we call it operator precedence.
Here's a quick lowdown on operator precedence:
- Operators that only involve one operand, such as NOT (!), are the first to be evaluated. (These are called unary operators if you want to know.)
- Next on the list are *, / and %.
- Then we have + and -
- Then come the comparison operators.
- Then the logical operators AND and OR.
- The last ones are the assignment operators.
If we want a certain operation to have higher precedence, we should use the grouping operator, which is a pair of round brackets: ()
. We've already met that before, when we learnt about assignment operators. Let's take another look at that example:
Code | Result |
---|---|
var a = 6;
var someNumber:Number = 3 + (a += 1);
trace(someNumber);
trace(a);
|
|
Here, a += 1 is given priority as it is enclosed in round brackets.
Without the brackets, it would result in an error:
Code | Result |
---|---|
var a = 6;
var someNumber:Number = 3 + a += 1;
trace(someNumber);
trace(a);
|
|
This is because var someNumber:Number = 3 + a
is performed first. var someNumber:Number = 3 + a
returns a value of 6. You can't assign a value to a constant, or the world would be a very chaotic place! That's why Flash will return an error.
What is operator associativity?
editConsider the expression someNumber = 3 * 2 + 5 * 6
. 3 * 2 and 5 * 6 have the same precedence, so which one should be performed first? Operator associativity answers this question. In this case, since the associativity of + is 'left to right', 3 * 2 is evaluated first, then 5 * 6, and finally 6 + 30.
The associativities of +, -, *, /, and % operators are all left to right, while those assignment are right to left.
Let's run a script with lots of operators to see the effects of operator precedence and associativity.
Code | Result |
---|---|
var someNumber:Number;
someNumber = 13 + 5 * 4;
trace(someNumber);
trace(1 + 3 / 5 != 2 && 4 - 3 >= 1);
|
|
In the assignment statement of someNumber, the computer evaluates 5 * 4 first, then 13 + 20.
The second trace is much more complicated. The operator with the lowest precedence here is &&, whose precedence is even lower than the comparison operators. The associativity of && is left to right, so the computer needs to evaluate the code on the left of && (1 + 3 / 5 != 2
) first. 1 + 3 / 5 = 1.6, which is not equal to 2. Therefore, the left side returns the value true
. Now to the right side. In 4 - 3 >= 1
, 4 - 3 = 1, so 1 >= 1 returns true
. Since both sides of the && are true, the trace statement returns true
.
How can I add a comment?
editNow that we've learnt all the difficult operators, let's end the chapter with a very simple concept.
A comment is some text that is added to the script to give information. They will be ignored by the compiler. The following example shows two types of comment:
Code | Result |
---|---|
/*This is just an example.
Don't actually copy-paste this into a Flash file.
There will be no visible results. */
var a = 6;
var someNumber:Number = 3 + (a += 1); //Assign the sum of 3 and a's new value to someNumber
|
|
The first comment, enclosed by /* and */, allows for multiple lines. /* marks the beginning of the comment and */ marks the end of it. This type of comment can also be added in the middle of a line. They are widely used for elements such as to-do lists and copyright information.
The second comment starts with // and is added to the end of the line. It cannot extend over one line. This type of comment is usually used to explain code.
Sometimes, we may want to 'hide' some code for testing or debugging. This process, called commenting out, is also achieved with comments.
Conclusion
editNow that we've learnt all our operators, we can move on to the next chapter: functions.
Notes
edit- ↑ & and | are valid operators (called bitwise operators, but they are beyond the scope of this book.