Adobe
Products

Top destinations

  • Adobe Creative Cloud
  • Creative Suite
  • Adobe Marketing Cloud
  • Acrobat
  • Photoshop
  • SiteCatalyst
  • Students
  • Elements family

Adobe Creative Cloud

  • What is Adobe Creative Cloud?
  • Design
  • Web
  • Photography
  • Video
  • Students
  • Teams
  • Enterprise
  • Educational institutions

Design and photography

  • Photoshop
  • Illustrator
  • InDesign
  • Adobe Muse
  • Lightroom

Video

  • Adobe Premiere
  • After Effects

Web development and HTML5

  • Edge Tools & Services [opens in a new window]
  • Dreamweaver
  • Gaming [opens in a new window]

Adobe Marketing Cloud

  • What is Adobe Marketing Cloud?
  • Digital analytics
  • Social marketing
  • Web experience management
  • Testing and targeting
  • Media optimization

Analytics

  • SiteCatalyst
  • Adobe Discover
  • Insight

Social

  • Adobe Social

Experience Manager

  • CQ
  • Scene7

Target

  • Test&Target
  • Recommendations
  • Search&Promote

Media Optimizer

  • AdLens
  • AudienceManager
  • AudienceResearch

Document services

  • Acrobat
  • EchoSign [opens in a new window]
  • FormsCentral [opens in a new window]
  • SendNow [opens in a new window]
  • Acrobat.com [opens in a new window]

Publishing

  • Digital Publishing Suite

  • See all products
Business solutions

By business need

  • Digital analytics
  • Digital publishing
  • Document management
  • Media optimization
  • Social marketing
  • Testing and targeting
  • Video editing and serving
  • Web development [opens in a new window]
  • Web experience management
  • See all business needs

By industry

  • Broadcast
  • Education
  • Financial services
  • Government
  • Publishing
  • Retail
  • See all industries
Support & Learning

I need help

  • Products
  • Adobe Creative Cloud
  • Adobe Marketing Cloud
  • Forums [opens in a new window]

I want to learn

  • Training and tutorials
  • Certification [opens in a new window]
  • Adobe Developer Connection
  • Adobe Design Center
  • Adobe TV [opens in a new window]
  • Adobe Marketing Center
  • Adobe Labs [opens in a new window]
Download
  • Product trials
  • Adobe Flash Player
  • Adobe Reader
  • Adobe AIR
  • See all downloads
Company
  • Careers at Adobe
  • Investor Relations
  • Newsroom
  • Privacy
  • Corporate Social Responsibility
  • Customer Showcase
  • Contact us
  • More company info
Buy
  • For personal and professional use
  • For students, educators, and staff
  • For small and medium businesses
  • Volume Licensing
  • Special offers
  • Adobe Marketing Cloud sales [opens in a new window]
Search
 
Info Sign in
Why sign in? Sign in to manage your account and access trial downloads, product extensions, community areas, and more.
Welcome,
My Adobe
My orders
My information
My preferences
My products and services
Sign out
My cart
Privacy My Adobe
Adobe
Products Sections Buy   Search  
Solutions Company
Help Learning
Sign in Sign out Privacy My Adobe
Preorder Estimated Availability Date. Your credit card will not be charged until the product is shipped. Estimated availability date is subject to change. Preorder Estimated Availability Date. Your credit card will not be charged until the product is ready to download. Estimated availability date is subject to change.
Qty:
Purchase requires verification of academic eligibility
Subtotal
Promotions
Estimated shipping
Tax
Calculated at checkout
Total
Review and Checkout
Adobe Developer Connection / ActionScript Technology Center / Learning ActionScript 3 /

ActionScript 3 fundamentals: Loops

by Michelle Yaiser

Michelle Yaiser
  • Adobe
  • michelleyaiser.com

Content

  • for loops
  • while loops
  • do..while loops
  • break and continue
  • Where to go from here

Created

7 November 2011

Page tools

Share on Facebook
Share on Twitter
Share on LinkedIn
Bookmark
Print
ActionScriptFlash BuilderFlash Professional
Was this helpful?
Yes   No

By clicking Submit, you accept the Adobe Terms of Use.

 
Thanks for your feedback.

Requirements

Prerequisite knowledge

You need to be familiar with ActionScript 3 variables, functions, objects, and conditionals.

User level

Beginning

Required products

  • Flash Builder (Download trial)
  • Flash Professional (Download trial)

A loop is a control structure that repeats a block of code multiple times. The loop stops when a condition you have specified is met. Loops are one of the most commonly used structures in programming. You will find many when you examine the code for any application. This article focuses on three types of loops in ActionScript 3: for , while , and do…while .

for loops

for loops are used in many programming languages. If you are familiar with C, C++, C# or Java, the for loop syntax in ActionScript 3 will look similar. A for loop consists of two main parts: a header and a body. The header contains the initialization, the test, and the update of the loop. Each part of the header is separated by a semicolon. The body contains the code that will be repeated by the loop.

Initialization

Each for loop has to be set up or initialized. The initialization statement runs once before looping begins. It declares and assigns the iteration variable. The iteration variable is the starting point for the counting the loop is going to do. It is commonly named i with a data type of int.

The iteration variable is like any other variable—you have to declare it before you can assign it a value. Don't forget to use the var keyword and assign it a data type. The data type of the iteration variable will depend upon the test and update of the for loop. int, uint, and Number are all valid types to use in a for loop.

If there is more than one for loop within a single function, the iteration variables will frequently be named i, j, k, and so on.

Examples of for loop initialization:

for(var i:int=0; ...){…} for(var i:int=9; ...){…} for(var j:int=1000000; ...){…} for(var k:uint=1026; ...){…} for(var l:Number=3.14; ...){…}

Test

Every for loop needs an end point. A conditional expression is used to determine when a loop should stop running. That test is evaluated at the beginning of each iteration. When the test evaluates to false, the loop stops and is exited.

You use comparison operators to define your test:

for(…; i<10; …){…} for(…; i<=10; …){…} for(…; i>10; …){…} for(…; i>=10; …){…}

When you use a literal number in your test, as in the examples above, your loop will run a known number of times. You can also use a variable that could change under different conditions:

for(…; i<array.length; …){…} for(…; i<totalUsers; …){…}

Update

When updating the iteration variable, for loops can count up using the increment operator ++, down using the decrement operator --, or by any number using the arithmetic compound assignment operators +=, -=, *=, /=, or %=.

Examples of for loop update statements:

for(…; …; i++){…} for(…; …; i--){…} for(…; …; i+=5){…} for(…; …; i-=7){…} for(…; …; i*=2){…} for(…; …; i/=10){…} for(…; …; i%=3){…}

Loop body

The code inside of the { } is considered the body of the loop. All of the code in the body of the loop will be executed during each iteration. Whatever code you would like to execute repeatedly is the code that you should put in the loop body.

for(…; …; …;){ trace(“Hello, world”); }

You can do calculations that vary, use the iteration variable to do something, call other functions, loop over an array, or instantiate objects—whatever code that needs to run over and over again. One thing to note: the code in the loop body should not change the value of the iteration variable. The loop's update statement in the header should be the only thing that changes the iteration variable.

Examples of for loops

Now that you understand the required parts of a for loop, look at some working examples of for loops and their output.

The for loop below simply traces the iteration variable. The loop will stop once i is no longer less than 10.

for(var i:int=0; i<10; i++){ trace(i); } //output 0 1 2 3 4 5 6 7 8 9

The for loop below also traces the iteration variable. This time the update statement decrements the iteration variable. The loop will stop once i is no longer greater than 10.

for(var i:int=20; i>10; i--){ trace(i); } //output 20 19 18 17 16 15 14 13 12 11

Once again, the for loop below traces the iteration variable. This time the update statement increments the iteration variable by 5. The loop will stop once i is no longer less than 20.

for(var i:int=0; i<20; i+=5){ trace(i); } //output 0 5 10 15

The for loop in the function below instantiates a new instance of a TextField (a core ActionScript 3 class) during each iteration. The iteration variable is used to set the x and y position of each instance. Because i changes each iteration, the x and y position will be different for each instance.

public function makeMessages():void{ for(var i:int=0; i<8; i++){ textMessage = new TextField(); textMessage.x = i * 10; textMessage.y = i * 30; textMessage.text = "hello"; addChild(textMessage); } } //values for x and y 0, 0 10, 30 20, 60 30, 90 40, 120 50, 150 60, 180 70, 210

Related to for loops are for..in and for each..in loops. Each of these loops are used to iterate through collections of data like Object, Array, and XMLList. Read more about them in the ActionScript 3.0 Reference at for..in and for each..in.

while loops

You use a for loop when you know exactly how many times you want a loop to run. But what if you don't know how many times something should happen? What if you want something to happen as long as a condition is true rather than for a set number of times? You would use a while loop in those situations. That type of loop continues to run as long as the conditional expression is true.

Unlike a for loop, a while loop does not have an iteration variable or an update in its header. You only write a conditional expression in the header of a while loop. You must set up the body of a while loop very carefully. The code in the body must eventually cause the conditional expression to become false or your while loop will never stop running and you will have an infinite loop.

Look at the code below. A variable— monthInAYear —is declared and assigned a value. That variable is used in the conditional expression for the while loop. In the body of the while loop, monthInAYear is incremented. It will eventually become larger than 12, therefore stopping the loop from running.

public var monthInAYear:int = 0; while(monthInAYear < 12) { trace(monthInAYear); monthInAYear ++; } //output 0 1 2 3 4 5 6 7 8 9 10 11

The conditional expression is only re-evaluated at the beginning of each iteration, not during. In other words, the conditional expression is only re-evaluated after all of the code in the loop body finishes executing. Therefore, whatever code causes the conditional expression to be false should be the last thing in the loop body. If it is not the last thing, the other code will be executed although the condition has become false. Compare the code example above with the one below. Notice the difference switching the order of the two statements in the loop body makes. When monthInAYear is 11, the conditional expression evaluates to true so the loop body is entered. Once inside the loop body, monthInAYear is incremented to 12, then traced. It is not until after the trace statement that the conditional expression is re-evaluated.

public var monthInAYear:int = 0; while(monthInAYear < 12) { monthInAYear ++; trace(monthInAYear); } //output 1 2 3 4 5 6 7 8 9 10 11 12

do..while loops

The do..while loop is very similar to a while loop. You use it when you want the code in the body to run at least once, regardless of the initial state of the condition. A do..while loop works in the following way:

  1. The statement runs
  2. Whatever is being tested is updated
  3. The conditional expression is declared following while
  4. If the conditional expression is true, the cycle continues
public var monthInAYear:int = 12; do{ trace(monthInAYear); monthInAYear++; }while(monthInAYear < 12); //output 12

break and continue

Sometimes you need to change the flow of a loop. Maybe you were looping over an array and you found the data you were searching for. Or maybe something in the application has changed and the loop is no longer necessary. ActionScript 3 has break and continue to use in those situations.

break

The break statement stops the loop immediately. Code in the loop body following the break statement is not executed. break stops the loop even if the result of the conditional expression in your loop is true. The code below shows break being used to exit the loop. Althought the loop is set up to run until i is no longer less than 23, the break statement causes it to stop when i is 13.

for(var i:int=1; i<23; i+=4){ if(i==13){ break; } trace(i); } //output 1 5 9

continue

The continue statement pauses the execution of the loop body, applies the loop's update, and then restarts the code in the loop body. The code below shows continue being used to skip an iteration of the loop. Notice that 13 is not in the output. When i is 13, continue causes the loop to pause, the update is applied making i 17, and then the loop continues.

for(var i:int=1; i<23; i+=4){ if(i==13){ continue; } trace(i); } //output 1 5 9 17 21

Using break and continue gives you more precise control over your loops.

Where to go from here

Whether you know exactly how many times a loop should run or under which conditions the loop should run, you can use loops to repeat a block of code multiple times. Understanding and using loops correctly allows you to perform operations that would be tedious or impossible if you had to hand-code each iteration. Loops are frequently used with objects, arrays, vectors, and XML data (coming soon).

More Like This

  • ActionScript 3 fundamentals: Operators
  • ActionScript 3 fundamentals: Packages
  • ActionScript 3 fundamentals: Arrays
  • ActionScript 3 fundamentals: Syntax
  • ActionScript 3 fundamentals: Variables
  • ActionScript 3 fundamentals: Data types
  • Garbage collection internals for Flash Player and Adobe AIR
  • AS3 fundamentals: Conditionals
  • ActionScript 3 fundamentals: Functions
  • ActionScript 3 fundamentals: Associative arrays, maps, and dictionaries

Products

  • Adobe Creative Cloud
  • Creative Suite
  • Adobe Marketing Cloud
  • Acrobat
  • Photoshop
  • Digital Publishing Suite
  • Elements family
  • SiteCatalyst
  • For education

Download

  • Product trials
  • Adobe Reader
  • Adobe Flash Player
  • Adobe AIR

Support & Learning

  • Product help
  • Forums

Buy

  • For personal and professional use
  • For students, educators, and staff
  • For small and medium businesses
  • Volume Licensing
  • Special offers

Company

  • News room
  • Partner programs
  • Corporate social responsibility
  • Career opportunities
  • Investor Relations
  • Events
  • Legal
  • Security
  • Contact Adobe
Choose your region United States (Change)
Choose your region Close

North America

Europe, Middle East and Africa

Asia Pacific

  • Canada - English
  • Canada - Français
  • Latinoamérica
  • México
  • United States

South America

  • Brasil
  • Africa - English
  • Österreich - Deutsch
  • Belgium - English
  • Belgique - Français
  • België - Nederlands
  • България
  • Hrvatska
  • Česká republika
  • Danmark
  • Eastern Europe - English
  • Eesti
  • Suomi
  • France
  • Deutschland
  • Magyarország
  • Ireland
  • Israel - English
  • ישראל - עברית
  • Italia
  • Latvija
  • Lietuva
  • Luxembourg - Deutsch
  • Luxembourg - English
  • Luxembourg - Français
  • الشرق الأوسط وشمال أفريقيا - اللغة العربية
  • Middle East and North Africa - English
  • Moyen-Orient et Afrique du Nord - Français
  • Nederland
  • Norge
  • Polska
  • Portugal
  • România
  • Россия
  • Srbija
  • Slovensko
  • Slovenija
  • España
  • Sverige
  • Schweiz - Deutsch
  • Suisse - Français
  • Svizzera - Italiano
  • Türkiye
  • Україна
  • United Kingdom
  • Australia
  • 中国
  • 中國香港特別行政區
  • Hong Kong S.A.R. of China
  • India - English
  • 日本
  • 한국
  • New Zealand
  • 台灣

Southeast Asia

  • Includes Indonesia, Malaysia, Philippines, Singapore, Thailand, and Vietnam - English

Copyright © 2013 Adobe Systems Incorporated. All rights reserved.

Terms of Use | Privacy | Cookies

Ad Choices

Reviewed by TRUSTe: site privacy statement