Home >
In order for software to be useful, it needs to be able to react to its environment. Put another way, a program needs to have logic. The logic of an application gives it the ability to change course when a given condition is met. Program flow in ActionScript 3.0 is controlled by conditionals and loops. Both conditionals and loops are responsible for determining whether a particular code block is executed, and are therefore placed within a method body. The main difference between the two is that conditionals decide on executing one collection of statements over another, and loops allow a collection of statements to execute over and over. As we'll soon see, loops, like many things in object-oriented programming, are great tools that provide the very important element of scalability. But first, a bit about conditionals.
ConditionalsThere are three basic conditional statements for use in ActionScript 3.0. They are: the "if, else" statement, the "if, else, if" statement, and the "switch" statement.
The "if, else" conditional allows your program to test for a stated condition, and then execute some determined block of code "if" the condition exists. If the condition does not exist, the "else" part of the conditional statement cues your program to execute some other block of code. Let's check out what the if, else code looks like, and break it down.
if (a == b)
{
doSomething();
}
else
{
doSomethingElse();
}
As it is, our code asks if a is equal to b. If that's true, the program should "do something". If it's not true that a equals b, then the program should "do something else". So put another way, if the value of the variable labeled "a" is equal to the value of the variable labeled "b" then the code block named "doSomething" is executed, otherwise the code block named "doSomethingElse" is executed.
An "if, else, if" conditional statement can ask if more than one condition is met. A code block can be executed if a condition is met, and then yet another code block can be executed if a different condition is instead met. It looks like this:
if (a == b)
{
doSomething();
}
else if (a == c)
{
doSomethingElse();
}
In this case, we are testing to see if a is equal to b, and if a is equal to c. If it turns out that a is equal to b, then the first code block is called. If that's not the case, but a happens to be equal to c, then the second code block is called.
Both "if, else", and "if, else, if" conditionals test for Boolean values, that is, whether it's true or not that a condition exists. A switch statement, on the other hand, doesn't need a Boolean value to be returned. Instead, it evaluates an expression and determines the correct code to execute based on the result.
var finishPlace : Result; // finishPlace is fetched from a service that our app uses
var myPlace : int = finishPlace.getPlace();
switch(myPlace)
{
case 0:
trace("First place - You're the champion!");
break;
case 1:
trace("Second");
break;
case 2:
trace("Third");
break;
case 3:
trace("Fourth");
break;
case 4:
trace("Fifth");
break;
default:
trace("sorry, you didn't make the top 5");
break;
}
This switch statement evaluates the results of the "getPlace" method as it applies to the "finishPlace" variable to determine the value of the "myPlace" variable. Since ActionScript is a "zero-based" language, our count can begin at zero, and be assigned a value of 1. The "switch(myPlace)" statement tells the compiler that a switch statement is in play. The "case" and "break" statements mark the beginning and end of each code block that may be called depending on the result that the getResult function returns. So basically, I'm asking the getResult method to find out what place I came in, and then asking the switch statement to let me know the results.
LoopsAs I said before, loops are another great tool in object-oriented programming that allow for scalability. A loop is simply the repetition, or iteration of a block of code. Ideally, all loops will have a point at which they come to a stop, but this isn't always the case, as we'll soon see. What makes loops such a valuable tool is the fact that in order to accomplish the same task without one, you'd have to write a huge amount of code. For example, let's say you'd like to create five hundred instances of a button when a user enters the correct information in a text field. (why not?) One way to do this is to simply to write a loop that calls the button's constructor method when the conditions are right, and then iterates five hundred times. It might look something like this:
var button : Button = null;
for ( var i : int = 0; i < 500 ; i++)
{
button = new Button();
// do something with button
}
Without the use of a loop, a programmer would have to write over 500 lines of code to do the same job that can be done in just a few.
ActionScript 3.0 employs the use of 5 different types of loops to control the flow of an application. They are: the "while" loop, the "do while" loop, the "for" loop, the "for..in" loop, and the "for each..in" loop.
The While LoopThe while loop allows a block of code to run continuously as long as a certain condition is met. In this case, the code block repeats over and over until the condition no longer exists. While loops can be tricky because they can create an infinite loop if not coded correctly, causing the program to crash. In order to avoid this, it's important to include a stop point for your loop. Consider the following example of a while loop:
var i : int = 0;
while (i < 50)
{
doSomething();
i++;
}
The first thing we see is a variable named "i". (It's common practice to name incrementing variables "i".) The variable "i" is an integer, and it's initial value is set to 0. Our loop says that "while the value of i is less than 50, loop away". For every iteration of the loop, the "doSomething" code block is carried out, and the variable i is incremented in value by 1. (The "++" operator means to increment by 1. You can also employ the "--" operator which means to decrement by 1.) Because we have included the "i++" statement, the value of i will continually increase on every iteration of the loop as long as it's less than 50. It won't loop again if it reaches 50 because of our conditional statement: while (i<50). While loops will compile, however, without a "i++" statement, unlike other loops. Of course, excluding the increment statement would result in an infinite loop, causing the program to crash.
Do..While LoopsMuch like while loops, do..while loops allow code to loop as long as a condition is met. The difference here is that a do..while loop allows the code to execute at least one time because the condition is not tested for until after the code is executed. Here's the code:
var i : int = 0;
do
{
someFunction(i);
i++;
}
while (i < 5);
For loops are used to iterate through a given range of values for a particular variable. Unlike while, and do..while loops, for loops require the inclusion of an expression that changes the variable's value on each iteration of the loop. In fact, for loops have three requirements: the variable with it's initial value, the conditional statement that explains the conditions necessary for looping, and the expression that changes the value of the variable. They are written like so:
var i : int;
for (i = 5; i < 50; i++)
{
someFunction();
}
Our loop says that someFunction should be performed when the value of i is between 5 and 50. Variable i will increase in value by 1 on every iteration of the loop, and the loop will cease once the value is not less than 50.
For..in LoopsFor..in loops are used to iterate through the properties of a generic object. Properties are not iterated over in any particular order since ActionScript doesn't store variable names in any particular order.
for (var i : String in someObject)
{
trace(i);
}
//output:
propertyNameOne
propertyNameTwo
propertyNameThree
For each..in loops are used to iterate through the values of items in a list, such as an XML document, an Array, or an ArrayCollection. The main difference between a for each..in loop and a for..in loop is that a for each..in loop iterates over the value of an item, and a for..in loop iterates over the variable name.
for each (var item : Object in someCollection)
{
trace(item);
}
//output:
[object Object]
[object Object]
[object Object]
We've discussed the basics of object-oriented programming and several points about the creation of classes in ActionScript, but before we can build even a simple application, we need to cover at least one more area. Our next post will discuss collections and arrays. Very soon we will have the skills needed to build simple widgets in ActionScript, and the background knowledge necessary for our journey deeper into the world of Flex.
Glossary of Termscase (expression) - Within a switch conditional statement, a case expression precedes every possible block of code that may be called.
Conditional - A special statement type used to control the flow of an application. A conditional statement tests for a given condition and allows a designated block of code to execute based on the validity of said condition.
do while (loop) - A type of while loop that allows at least one execution of a code block due to the fact that the condition isn't tested until after the code block is executed.
for (loop) - A loop that iterates through a specific range of values.
for..in (loop) - A loop that iterates through an object's variables.
for each..in (loop) - A loop that iterates through the values of items in a collection.
if, else - The most basic type of conditional statement. An if, else conditional tests for a certain condition, and if it finds it, executes a given code block. If the condition is not found, an alternate code block is executed.
if, else, if - A conditional statement that is able to test for multiple conditions, not simply the presence or absence of one condition.
Iterate - Simply, to do once again. In regards to looping, to iterate is to run through one round of the loop.
loop - A method to provide program flow in which conditions are tested for and code blocks are executed a certain number of times.
switch - A type of conditional statement in which the code block to be executed can be any number of different possible outcomes depending on the value returned in the conditional.
trace () function - A top level function that displays expressions, or writes to log files while debugging.
while (loop) - A loop that allows a code block to be executed as long as a given condition is met.




Facebook Application Development
Don't forget the conditional ternary operator!
x = ( a == b ) ? y : z;
If a equals b, then x will equal y, else x will equal z.
I would also mention the break and continue keywords that can appear in for, for in, for each and while loops.
The break keyword will terminate a loop. It usually is used together with conditionals to exit a loop before it reaches its natural end. Ex. when searching for a property of an object in a for in loop, once the property is found, break be used to end the loop immediately.
The continue keyword will not end a loop, but instead it will terminate one iteration without executing any more statements, and start the next one.
great article! i'm a flash teacher and will send this link out to my students. one note: the code formatting for the loops section is all very strange. it would be great to clean up the indenting -- it's better practice, and much easier for beginners to read.
@andrew
Nice point.. thanks man.. We kind of wanted to cover the basics in this post since the series is targeted at non-programmers, but it was probably an oversight to not at least mention the ternary operator. It is one of my favorite geeky cool conditionals.
@bartek
Thanks for mentioning this. I actually tend to avoid using break and continue, but sometimes it's very effective to use them. They kind of remind me of using a goto statement back in the BASIC / Pascal days.
I think especially for a beginning programmer it's a little more intuitive to build that kind of logic into the conditional of the loop. Although, if you're tuning for efficiency break and continue can be a good choice. (IMHO)
@kathryn
Thanks for reading... yeah we'll try and get the indenting style more consistent with best practices. When we post sample Flex apps view source will be enabled and that code should reflect all the best practices.
hi there, listen im stuck with an issue here.... im doing a horizontal sliding menu using actionscript 3.0, and well i wanted to know if i can use two conditions inside an if e.g :
function mover2(e:MouseEvent):void
{
****** if(concepto_mc.y == 54.6, contacto_mc.y = 88.3)
{
new Tween(contacto_mc,"y", Strong.easeInOut, 88.3, 267.2, 4, true);
}
if(concepto_mc.y == 54.6)
{
new Tween(contacto_mc,"y", Strong.easeInOut, 88.3, 267.2, 4, true);
new Tween(senza_mc,"y", Strong.easeInOut, 122, 300.8, 4, true);
}
if(concepto_mc.y == 233.6)
{
new Tween(concepto_mc,"y", Strong.easeInOut, 233.6, 54.6, 4, true);
}
}
it does not seem to work, so i wanted to know if that can actually be used or im just wasting my time, or if there is another way to do this...
help will be great
hi there, listen im stuck with an issue here.... im doing a horizontal sliding menu using actionscript 3.0, and well i wanted to know if i can use two conditions inside an if e.g :
function mover2(e:MouseEvent):void
{
****** if(concepto_mc.y == 54.6, contacto_mc.y = 88.3)
{
new Tween(contacto_mc,"y", Strong.easeInOut, 88.3, 267.2, 4, true);
}
if(concepto_mc.y == 54.6)
{
new Tween(contacto_mc,"y", Strong.easeInOut, 88.3, 267.2, 4, true);
new Tween(senza_mc,"y", Strong.easeInOut, 122, 300.8, 4, true);
}
if(concepto_mc.y == 233.6)
{
new Tween(concepto_mc,"y", Strong.easeInOut, 233.6, 54.6, 4, true);
}
}
it does not seem to work, so i wanted to know if that can actually be used or im just wasting my time, or if there is another way to do this...
help will be great
hi there, listen im stuck with an issue here.... im doing a horizontal sliding menu using actionscript 3.0, and well i wanted to know if i can use two conditions inside an if e.g :
function mover2(e:MouseEvent):void
{
****** if(concepto_mc.y == 54.6, contacto_mc.y = 88.3)
{
new Tween(contacto_mc,"y", Strong.easeInOut, 88.3, 267.2, 4, true);
}
if(concepto_mc.y == 54.6)
{
new Tween(contacto_mc,"y", Strong.easeInOut, 88.3, 267.2, 4, true);
new Tween(senza_mc,"y", Strong.easeInOut, 122, 300.8, 4, true);
}
if(concepto_mc.y == 233.6)
{
new Tween(concepto_mc,"y", Strong.easeInOut, 233.6, 54.6, 4, true);
}
}
it does not seem to work, so i wanted to know if that can actually be used or im just wasting my time, or if there is another way to do this...
help will be great
Question for any of you...
Can you put conditionals in a SWITCH statement?
such as:
switch (nextQ) {
Case 0:
if(myTarget =="resp1"){
output = myQuestionList.text[1];
question_txt.text=output;
outputQ = myQuestionList.text[1];
visibleQ = myQuestionList.number[1].valueOf();
break;
}
Question for any of you...
Can you put conditionals in a SWITCH statement?
such as:
switch (nextQ) {
Case 0:
if(myTarget =="resp1"){
output = myQuestionList.text[1];
question_txt.text=output;
outputQ = myQuestionList.text[1];
visibleQ = myQuestionList.number[1].valueOf();
break;
}
Question for any of you...
Can you put conditionals in a SWITCH statement?
such as:
switch (nextQ) {
Case 0:
if(myTarget =="resp1"){
output = myQuestionList.text[1];
question_txt.text=output;
outputQ = myQuestionList.text[1];
visibleQ = myQuestionList.number[1].valueOf();
break;
}
Question for any of you...
Can you put conditionals in a SWITCH statement?
such as:
switch (nextQ) {
Case 0:
if(myTarget =="resp1"){
output = myQuestionList.text[1];
question_txt.text=output;
outputQ = myQuestionList.text[1];
visibleQ = myQuestionList.number[1].valueOf();
break;
}