Adobe
Products
Acrobat
Creative Cloud
Creative Suite
Digital Marketing Suite
Digital Publishing Suite
Elements
Photoshop
Touch Apps
Student and Teacher Editions
More products
Solutions
Creative tools for business
Digital marketing
Digital media
Education
Financial services
Government
Web Experience Management
More solutions
Learning Help Downloads Company
Buy
Home use for personal and home office
Education for students, educators, and staff
Business for small and medium businesses
Licensing programs for businesses, schools, and government
Special offers
Search
 
Info Sign in
Welcome,
My cart
My orders My Adobe
My Adobe
My orders
My information
My preferences
My products and services
Sign out
Why sign in? Sign in to manage your account and access trial downloads, product extensions, community areas, and more.
Adobe
Products Sections Buy   Search  
Solutions Company
Help Learning
Sign in Sign out My orders 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
Review and Checkout
Adobe Developer Connection / ActionScript Technology Center / Learning ActionScript 3 /

AS3 fundamentals: Conditionals

by Michelle Yaiser

Michelle Yaiser
  • Adobe
  • michelleyaiser.com

Content

  • if statements
  • if..else statements
  • if..else if..else statements
  • switch statements
  • Where to go from here

Created

7 November 2011

Page tools

Share on Facebook
Share on Twitter
Share on LinkedIn
Bookmark
Print
ActionScript Adobe AIR Flash Builder 4.5 Standard Flash Player Flash Professional

Requirements

Prerequisite knowledge

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

User level

Beginning

Required products

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

You use conditional logic every day. Do you turn left or right? Do you eat breakfast? If the line is short enough, you wait, else you come back later. These types of decisions are necessary to make it through your day and equally necessary to make any program or application you create function and interact with users.

Conditional logic is simply the written expression of these same decisions within your program. It can take a simple form, such as: if the line is short, wait. Or a more complicated one, such as: if the line is less than five people, or more than five people but moving quickly, wait. In either case, the goal is to clearly indicate the conditions under which certain actions should occur.

Within programming, those decisions are called conditional expressions. The conditional expressions you write must evaluate to either true or false. The answer to the conditional expression will determine which block of code will execute. This article will cover how to write conditional expressions and the conditional statements that use them.

if statements

The if statement asks a single question. If the answer to that question is true and only if the answer is true, then the associated code is executed. If the answer is false, the associated code block is ignored and the next statement outside of the if statement is executed.

To write an if statement, start with if, followed by a set of parentheses around the conditional test you want to evaluate. Then use curly brackets to denote the code block you want to run if the condition is true. Look at the sample code below.

if (n>1){
 trace("Conditional expression is true"); }


Conditional expressions frequently use the equality and comparison operators: == , != , === , !== , < , <= , > , and >= . You can also use the logical operators: && (logical AND) and || (logical OR). See ActionScript 3 fundamentals: Operators for more information on these operators. The code below shows the value of a variable being compared to 5 using the less than operator.

public function ageTest():void{ var age:int = Math.random()*10; if (age<5){ trace("You are too young"); } }

The code below shows logical operators being used in the conditional expressions. The first function uses AND logic. The second one uses OR logic.

public function usingANDLogic():void{ var randomNumber:int = Math.random()*10 + 1; if(randomNumber>3 && randomNumber<8 ){ trace("randomNumber is between 3 and 8. It is " + randomNumber); } } public function usingORLogic():void{ var randomNumber:int = Math.random()*10 + 1; if(randomNumber<3 || randomNumber>8 ){ trace("randomNumber is either less than 3 or greater than 8. It is " + randomNumber); } }

Because conditional expressions evaluate to either true or false and Boolean variables can only contain either true or false, you can check the state of a Boolean variable without using any comparison or logic operators. Just use the name of the variable within the parentheses following if. If the variable contains true, the associated code block executes.

public function doYouLikeProgramming():void{ var likesProgramming:Boolean = true; if(likesProgramming){ trace("I like to program too"); } }

if..else statements

Sometimes you want the program to do one thing if the conditional expression is true and another thing if the conditional expression is false. You use an else statement to execute code if the conditional expression tested by if is false. Look at the code below. Notice that a second conditional expression is not used with else.

if(n>10){
 trace("Bigger than 10"); }
else{ trace("Less than 10"); }

In the code below, the variable guess is tested to see if its value is equivalent to the value of magicNumber. You would use similar code to test a value entered by the application's user.

public var guess:int = 8; public function testGuess():void{ var magicNumber:int = 7; if(guess==magicNumber){ trace("You are correct"); } else{ trace("Sorry, try again."); } }

if..else if..else statements

You can test multiple conditions using if..else if..else statements. Once a condition evaluates to true, the code in that condition's block is executed, and the if..else if..else statement is exited.

The value of the variable candyPieces is tested in the code below. The first if statement checks to see if the value is less than or equal to 3. If it is, "You only have a few pieces" appears in the output window, and the if..else if..else statement is exited. If the value is not less than or equal to 3, candyPieces is checked to see if its value is less than or greater than 10. Again, if the answer is true, the associated code if executed. If the answer is false, the next test is run. If none of the conditional statements evaluate to true, the code in the else block is executed.

public function howMuchCandy():void{ var candyPieces:int = Math.random()*50; if(candyPieces <= 3){ trace("You only have a few pieces"); } else if(candyPieces <= 10){ trace("You have a handful of candy"); } else if(candyPieces <= 25){ trace("You have some candy"); } else if(candyPieces <= 35){ trace("You have lots of candy"); } else{ trace("You have lots and lots of candy."); trace("Can I have some?"); } }

switch statements

If you have a set list of possibilities and each one has a different outcome, you can a use switch statement rather than a series of if..else if..else statements.

Each possible outcome is a case in your switch statement. Each case must end with break statement. In if statements only the code enclosed in the curly brackets {} is executed when a condition is true. switch statements do not use curly brackets so break is used to stop the conditional statement from proceeding to the next case and exit the switch statement.

Although it is not required, it is good practice to use a default case to exit the switch statement in case none of the possible outcomes occur. If none of the cases are true, the default case will execute, preventing an infinite loop. The default case must be the last option so the switch statement is not exited before all cases are tested.

In the example below, the variable grade is tested against the possible grades a student could earn. Remember that when you work with string values, they are always in quotes. Thus, the value for each case is in quotes.

public function gradeSwitch():void{ var grade:String = "D"; switch(grade){ case "A": trace("Great job - you are getting an A"); break; case "B": trace("good job - you are getting a B"); break; case "C": trace("average - you are getting a C"); break; case "D": trace("work harder - you are getting a D"); break; case "F": trace("I'm sorry - you are failing"); break; default: trace("Invalid data"); break; } }

Where to go from here

Conditional logic can be expressed in multiple forms, but all forms have the same goal: to clearly indicate the conditions under which certain actions should occur. Conditional logic is a core technique required to develop programs and applications of any complexity. Conditional expressions are often used in combination with loops and to search for data in objects, arrays, vectors, and XML data (coming soon).

More Like This

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

Products

  • Acrobat
  • Creative Cloud
  • Creative Suite
  • Digital Marketing Suite
  • Digital Publishing Suite
  • Elements
  • Mobile Apps
  • Photoshop
  • Touch Apps
  • Student and Teacher Editions

Solutions

  • Digital marketing
  • Digital media
  • Web Experience Management

Industries

  • Education
  • Financial services
  • Government

Help

  • Product help centers
  • Orders and returns
  • Downloading and installing
  • My Adobe

Learning

  • Adobe Developer Connection
  • Adobe TV
  • Training and certification
  • Forums
  • Design Center

Ways to buy

  • For personal and home office
  • For students, educators, and staff
  • For small and medium businesses
  • For businesses, schools, and government
  • Special offers

Downloads

  • Adobe Reader
  • Adobe Flash Player
  • Adobe AIR
  • Adobe Shockwave Player

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 © 2012 Adobe Systems Incorporated. All rights reserved.

Terms of Use | Privacy Policy and Cookies (Updated)

Ad Choices

Reviewed by TRUSTe: site privacy statement