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

Using Parentheses to Force Order

You can force the earlier example to follow the order of operation that results in the value of 1.5. You can use parentheses to group calculations together. In the order of operations, math operations that are grouped within a pair of parentheses are always calculated first.

You can adjust the example to get the 1.5 that you originally calculated by performing the calculations from left to right:

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

Now instead of skipping the first addition action, the Flash runtime calculates what is inside the parentheses first and then continues across, as shown in Figure 4.4.

as3_4_4.jpg

Figure 4.4 Forcing the order with parentheses using order of operations

When the Flash runtime looks at the ActionScript, it starts with the first set of parentheses it finds:

  • 2 + 3 = 5, which is the only set of parentheses 1.jpg

It then starts back at the beginning with multiplication, division, and modulo:

  • 5 x 2 = 10 2.jpg
  • 10 / 4 = 2.5 3.jpg

Now that it is finished with multiplication, division, and modulo, it starts back on the left and evaluates addition and subtraction:

  • 2.5 - 1 = 1.5 4.jpg

You end up with 1.5 5.jpg, which is then sent to the Output panel.

You can nest parentheses within each other, but just make sure that every opening parenthesis has a matching closing parenthesis. This is one of the most common bugs you'll find in your programs, unmatched parentheses and braces.

  • + Share This
  • 🔖 Save To Your Account