ActionScript 3.0 Cookbook: Chapter 1: ActionScript Basics
Pages: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10

Discussion

Often you'll want the new value of a variable or property to depend on the previous value. For example, you might want to move a sprite to a new position that is 10 pixels to the right of its current position.

In an assignment statement--any statement using the assignment operator (an equals sign )--the expression to the right of the equals sign is evaluated and the result is stored in the variable or property on the left side. Therefore, you can modify the value of a variable in an expression on the right side of the equation and assign that new value to the very same variable on the left side of the equation.

Although the following may look strange to those who remember basic algebra, it is very common for a variable to be set equal to itself plus some number:

// Add 6 to the current value of quantity, and assign that new 
// value back to quantity. For example, if quantity was 4, this 
// statement sets it to 10.
quantity = quantity + 6;

However, when performing mathematical operations, it is often more convenient to use one of the compound assignment operators, which combine a mathematical operator with the assignment operator. The +=, -=, *=, and /= operators are the most prevalent compound assignment operators. When you use one of these compound assignment operators, the value on the right side of the assignment operator is added to, subtracted from, multiplied by, or divided into the value of the variable on the left, and the new value is assigned to the same variable. The following are a few examples of equivalent statements.

These statements both add 6 to the existing value of quantity:

quantity = quantity + 6;
quantity += 6;

These statements both subtract 6 from the existing value of quantity:

quantity = quantity - 6;
quantity -= 6;

These statements both multiple quantity by factor:

quantity = quantity * factor;
quantity *= factor;

These statements both divide quantity by factor:

quantity = quantity / factor;
quantity /= factor;

There should be no space between the two symbols that make up a compound assignment operator. Additionally, if you are incrementing or decrementing a variable by 1, you can use the increment or decrement operators.

This statement adds 1 to quantity:

quantity++;

and has the same effect as either of these statements:

quantity = quantity + 1;
quantity += 1;

This statement subtracts 1 from quantity:

quantity --;

and has the same effect as either of these statements:

quantity = quantity - 1;
quantity -= 1;

You can use the increment and decrement operators ( -- and ++) either before or after the variable or property they operate upon. If used before the operand, they are called prefix operators. If used after the operand, they are called postfix operators. The prefix and postfix operators modify the operand in the same way but at different times. In some circumstances, there is no net difference in their operation, but the distinction is still important in many cases. When using prefix operators, the value is modified before the remainder of the statement or expression is evaluated. And if you're using postfix operators, the value is modified after the remainder of the statement has executed. Note how the first example increments quantity after displaying its value, whereas the second example increments quantity before displaying its value:

var quantity:Number = 5;
trace(quantity++);  // Displays: 5
trace(quantity);    // Displays: 6

var quantity:Number = 5;
trace(++quantity);  // Displays: 6
trace(quantity);    // Displays: 6

Getting back to the original problem, you can use these operators to modify a property over time. This example causes the specified sprite to rotate by five degrees each time the method is called:

private function onEnterFrame(event:Event) {
  _sprite.rotation += 5;
}

Note that in ActionScript 3.0, you would have to add an event listener to the enterFrame event and set this method as the event handler for this to work properly. See Recipe 1.5 for information on how to handle the enterFrame event.

See Also

Recipe 1.5


This excerpt is from ActionScript 3.0 Cookbook. Well before Ajax and Windows Presentation Foundation, Macromedia Flash provided the first method for building "rich" web pages. Now, Adobe is making Flash a full-fledged development environment, and learning ActionScript 3.0 is key. That's a challenge for even the most experienced Flash developer. This Cookbook offers more than 300 solutions to solve a wide range of coding dilemmas, so you can learn to work with the new version right away.

buy button

Section 1.8: Checking Equality or Comparing Values

Problem

You want to check if two values are equal.

Solution

Use the equality (or inequality) or strict equality (or strict inequality) operator to compare two values. To check whether a value is a valid number, use isNaN( ).

Discussion

Equality expressions always return a Boolean value indicating whether the two values are equal. The equality (and inequality) operators come in both regular and strict flavors. The regular equality and inequality operators check whether the two expressions being compared can be resolved to the same value after converting them to the same datatype. For example, note that the string "6" and the number 6 are considered equal because the string "6" is converted to the number 6 before comparison:

trace(5 == 6);    // Displays: false
trace(6 == 6);    // Displays: true
trace(6 == "6");  // Displays: true
trace(5 == "6");  // Displays: false

Note that in a project with default settings, the previous code example won't even compile. That's because it is compiled with a strict flag, causing the compiler to be more exact in checking datatypes at compile time. It complains that it is being asked to compare an int with a String. To turn off the strict flag, go to the ActionScript Compiler section of the project's properties, and uncheck the box next to "Enable compile-time type checking (-strict)". It is suggested, however, that you leave this option on for most projects, as it gives you better protection against inadvertent errors.

The logical inequality operator (!=) returns false if two values are equal and true if they aren't. If necessary, the operands are converted to the same datatype before the comparison:

trace(5 != 6);    // Displays: true
trace(6 != 6);    // Displays: false
trace(6 != "6");  // Displays: false
trace(5 != "6");  // Displays: true

Again, this example only compiles if strict type checking is disabled.

On the other hand, if you have turned off the strict flag, but you want to perform a strict comparison in one section of code, you can use the strict equality and inequality operators, === and !==. These first check whether the values being compared are of the same datatype before performing the comparison. Differences in datatypes causes the strict equality operator to return false and the strict inequality operator to return true:

trace(6 === 6);    // Displays: true
trace(6 === "6");  // Displays: false
trace(6 !== 6);    // Displays: false
trace(6 !== "6");  // Displays: true

There is a big difference between the assignment operator (=) and the equality operator (==). If you use the assignment operator instead of the equality operator, the variable's value will change rather than testing its current value.

Using the wrong operator leads to unexpected results. In the following example, quantity equals 5 at first, so you might expect the subsequent if statement to always evaluate to false, preventing the trace( ) from being executed:

var quantity:int = 5;
// The following code is wrong. It should be if (quantity == 6) instead
if (quantity = 6) {
  trace("Rabbits are bunnies.");
}
trace("quantity is " + quantity);  // Displays: quantity is 6

However, the example mistakenly uses the assignment operator (=) instead of the equality operator (==). That is, the expression quantity = 6 sets quantity to 6 instead of testing whether quantity is 6. When used in an if clause, the expression quantity = 6 is treated as the number 6. Because, any nonzero number used in a test expression converts to the Boolean true, the trace( ) action is called. Replace the test expression with quantity == 6 instead. Fortunately, the ActionScript 3.0 compiler is smart enough to recognize this common error and although the code still compiles, you aren't given a warning.

You can check an item's datatype using the is operator, as follows:

var quantity:int = 5;
if (quantity is int) {
  trace("Yippee. It's an integer.");
}

Note that the new ActionScript 3.0 types int and uint will also test positive as Numbers.

However, some numeric values are invalid. The following example results in quantity being set equal to NaN (a constant representing invalid numbers, short for not a number) because the calculation cannot be performed in a meaningful way:

var quantity:Number = 15 - "rabbits";

Despite its name, NaN is a recognized value of the Number datatype:

trace(typeof quantity);   // Displays: "number"

Therefore, to test if something is not just any number, but a valid number, try this:

var quantity:Number = 15 - "rabbits";
if (quantity is Number) {

  // Nice try, but this won't work
  if (quantity != NaN) {
    trace("Yippee. It's a number.");
  }
} 

However, you can't simply compare a value to the constant NaN to check whether it is a valid number. The ActionScript 3.0 compiler even gives you a warning to this effect. Instead, you must use the special isNaN( ) function to perform the test.

Pages: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10

Next Pagearrow