Publishers of technology books, eBooks, and videos for creative people

Home > Articles > Design > Adobe Creative Suite

  • Print
  • + Share This
This chapter is from the book

Order of Operations

By default, mathematical functions do not run from left to right, but follow a specific order of operations. You may recall from math classes that certain mathematical functions are calculated before others, regardless of their left-to-right order.

  1. Create a new ActionScript 3.0 project and enter in the following code for the project:

    // Order of Operations
    var answer:Number = 2 + 3 * 2 / 4 - 1;

    In this example, you have a number of math functions that are running from left to right. If you don't follow the order of operations and evaluate it from left to right, you get 1.5, as shown in Figure 4.2.


    Figure 4.2 Incorrect left-to-right order of operations

  2. Run the code. You'll see what might seem unexpected: 2.5. Why? Because certain math functions are executed before others. In fact, this is the order:

    1. Multiplication, Division, and Modulo
    2. Addition and Subtraction

    All the multiplication, division, and modulo operations are processed from left to right to the end. Then calculation starts again from the left and processes addition and subtraction. Look at Figure 4.3 to see how this works.


    Figure 4.3 Correct order of operations for the evaluation

When the Flash runtime looks at the ActionScript, it starts from the left, evaluating the expression:

  • It ignores the 2 + 3, since the rules dictate processing only multiplication, division, and modulo at this point.
  • 3 x 2 = 6 1.jpg
  • 6 / 4 = 1.5 2.jpg

Since there are no more multiplication, division, or modulo operations, it returns to the beginning and processes addition and subtraction.

  • 2 + 1.5 = 3.5 3.jpg
  • 3.5 - 1 = 2.5 4.jpg

You have the final result, 2.5 5.jpg, which is then sent to the Output panel.

You can alter the order of operation by using parentheses. This will force Flash to adopt a specific path of calculating the results. You'll learn about overriding the order of operation rules in the next section.

  • + Share This
  • 🔖 Save To Your Account