Chapter 2. Conditionals and Loops

In this chapter, we'll depart from the general topics of classes and objects. Instead, we'll focus, on two essential types of statements: conditionals and loops. Conditionals are used to add logic to a program, while loops are used to perform repetitive tasks. Both conditionals and loops are extremely common, and can be found in nearly every ActionScript program. Once we've finished with conditionals and loops, we'll return to classes and objects, and continue developing our virtual zoo program.

This chapter presents all code examples outside the context of a functioning class or program. However, in a real program, conditionals and loops can be used within instance methods, constructor methods, static methods, functions, directly within class bodies or package bodies, and even outside package bodies.


A conditional is a type of statement that executes only when a specified condition is met. Conditionals let a program choose between multiple possible courses of action based on the current circumstances.

ActionScript provides two different conditionals: the if statement and the switch statement. ActionScript also provides a single conditional operator, ?:, which is covered briefly in Chapter 10. For details on the ?: operator, see Adobe's ActionScript language reference.

The if Statement

The if statement is like a two-pronged fork in the road. It contains two blocks of code and an expression (known as the test expression) that governs which ...

Get Essential ActionScript 3.0 now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.