Flash Essential

AS3 Guide Conditionals

Aug 6th 2008
9 Comments
respond
trackback

Show Navigation || Hide Navigation

Often when you're writing code their will be times when you need to make decisions in your code. You might want a certain piece of code to execute under a certain circumstance and another piece of code to execute under different circumstances. ActionScript 3.0 uses conditionals to deal with these situations. To simplify ActionScript creates a test asking whether conditions are met, if the condition is met the test will evaluate to true and if the condition is not met alternative action is taken.

The if Statement

The most frequently used condition you will notice when looking at code is the if statement.

Example;

var postNumber:Number = 56;
var siteName:String = ("Flash Essential")
if(siteName == "Flash Essential")
{
trace ("the site name is correct")};

Tip; If you aren't sure what var ect means visit our Variables chapter.

Inside the parentheses you'll notice two equals signs. These equals signs essentially mean "is equal to?" So the above test is asking if the siteName string is equal to Flash Essential, which of course it is therefore "the site name is correct" is traced in the output window. if statements are about finding the truth in your code, these type of equations if you will are known as Comparison Operators below are a list of other Comparison Operators.

== is equal to

< is less than

> is greater than

>= is greater than or equal to

<= is less than or equal to

!= is not equal to

You can also use Logical Operators inside the parentheses, below are some example of Logical Operators.

(%%) And

(||) Or

(!) Not

So with comparison and Logical Operators it gives you the chance to ask questions. Both can work side by side in your code with relative ease.

Example;

var postNumber:Number = 56;
var siteName:String = ("Flash Essential")
if( postNumber == 56 %% siteName == "Flash Essential")
{
trace("correct");
}

else Statement

So what happens if you want some code to execute if the code returns a false value or doesn't add up? For this we use the else statement. Lets take a look at the else statement in action.

Example;

var postNumber:Number = 56;
var siteName:String = ("Flash Essential")
if( postNumber == 40){
trace("The post number is 56″);
}
else{
trace("This isnt post number 56″)
}

So the code evaluates the if statement, sees that it's had a false return value so executes the code in the else statement. The else statement basically allows you the option of having a "true no matter what" equation in your code.

else if Statement

You might want to execute more than one if statement but since we can only use one if statement and one additional else statement, we use the else if statement because we can use as many of these as we please.

Example;

var postNumber:Number = 56;
var siteName:String = ("Flash Essential")
if( postNumber == 56){
trace("The post number is 56″);
}
else if (siteName == "Flash Essential");
else{
trace("This isnt post number 56″);
}

In this case the first trace statement would execute because it's the first truth in the code. If perhaps you wanted more code to be executed you would need to use more conditionals in the code.

Reference; See the if and else statements in Step 5 of the MP3 Player Tutorial

switch

As you may have noticed if statements can be rather bulky and can take a while to read through, this can be a particular pain when coming back to old code you haven't seen in a while. An alternative method is to use the switch statement.

Example;

var postNumber:Number = 56;
var siteName:String = ("Flash Essential")
switch (siteName){
case "Flash Essential" :
trace("Site name is flash essential");
break
case "Flash Site" :
trace("Site name is Flash site");
break
case "Flash blog" :
trace("Site name is Flash site");
break
}

switch contains the object you want to evaluate or test, the case line represents the possible value and the trace statement we already know executes if the test is successful.


This post is tagged , , , , , ,



Sponsors

Explore Recent





Monthly Archives



Friends and Affiliates



9 Comments

  1. Hey i dont think in %% could be used for And because they represent modulus.
    its normally && please confirm if im wrong
    surf
    ;)

  2. Hi! I was surfing and found your blog post… nice! I love your blog. :) Cheers! Sandra. R.

  3. Takeda Shingen

    Wow.. this what i'm searching. Simple, to the point, clean and clear. Nice job bro…

Leave a Reply

auto battery discharge cold
blake holman sioux falls sd
ameican pitbull terrier
character story elements powerpoints
construct a wheelchair ramp
paralysis.org
bangladesh orphanages
2000 lb bomb
kristi rowley
concrete acid etching supplies
bossier city la real estate
bedford indiana job openings
cordura bags 2008 hayabusa
hana kimi direct downloads
07 tahoe lug pattern
stroke-jobs.com
2008 satilite map
arctic zone lunch bag
04 g35 body kit vader 3
blackpool town fc
reserved sugar
animal control in evansville
1927 roadster
myspacelayouts.net
cast costumes for hello dolly
art for the heart fundraising
treesforyou.org
agape gaddis
1080p 24 lcd monitor
etymotic.com
article about dpms lr 308
27713 nc zip code
boo creepy foot doctor
convicted offenders listed in british columbia
daybed covers toile
job predict
butas sa pinto silipan
0 andreas test residence
foxpro serial port fll
dr natura and oldest man
2000 mercury sable too lean
frozen liquid longest
2003 exotic spices calendar
1 bedroom suite orlando
1 2 inch vinyl micro blinds
colleges that teach veterinarian toxicology
dieter klimm germany
3 cm dialated
captain william fowler
mmahq.com
1st lady on my
ancient mayan popol vuh
pinky and the brain avatar
claire pruitt doll patterns
xbux.com
av 2009 virus blocking malware bytes
2002 mountain aire 4097 floorplan
emeritus restraint policy
arizona diamond backs fan club
ftd florists oneida ny
courier service pretoria rundu luanda
insane clown posse downloads
bello pr-25 review
4 bedroom rental in yorba linda
5 estacion flores de alquiler video
americus vespucius
ati modified driver vista 32
adoption paralegal in toronto
dish pvr 501 mod
1800 daniel brothers in tn
irony.com
dominant bodybuilding females
custody911.com
adm buyout
alex moulton mark 1
hughesspeednet.com
byron hinton
shoehunting.com
experiment on rl circuit
1296 mhz power amplifier circuits
7th level of hell survey
constitutional class
anemia and skin itch
goofy gold download
webshapes.org
car jacks 3.5 ton costco
neopostinc.com
brookfield athletic shoe company inc
cause transaction lagging bank reconciliation
fire at mann gulch
ambridge duck hunting
application coding wikipedia
12 1 2 womens cowboy boot
cci cb short
before the hammer strikes the nail
interpretation of low oxygen saturation
autosearch.com
outrigger condos
carl erickson pole vault camps
matchmaker pittsburgh pa
cheats gba pokemon emerald
and eminem forgot about dre
howtomaketime.com
andorra property
1939 indian scout timing specs
diet plans for chronic indigestion
applied kinesiology for hiatal hernia
read socrates in love online free
nutone-home.com
air europa seating arrangements
8 configuration sacral fracture
assfucked to tears
alto sax 575 allegro
geological features in the appalachians
bill clinton comment obama
addicting games territory war
irc mythos cx slick 700x42c
msn messenger signup
kissed his feet bet
apache2 debian etch amd64
bnvillage.co.uk
do horses have treat preferences
10mb network
cantv.net
noel chance racehorse winners at warrick
cmu waterproofing techniques
brenda adams bebo
1967 ford shelby mustang pics
charlotte witt
13th century mens clothing france
embassyhomepage.com
blood draining out nasal passages
sprinklerfitters669.org
stephan a rhodes
cemeteries in holyoke ma
gallstone purge
emma tryon
amboy washington mptels
branson ultra sonic cleaner
anti-tank obstacle
chris mcgee
auto dealers mit
belle meade united methodist
hotel regent paris
smdailyjournal.com
1995 ford f150 sputters on acceleration
dan sommer in omaha nebraska
academy of our lady chicago il
accrual method 12 month membership
1941 luger manufacturing plants
curry mussels
construction-business-forms.com
gym clothing catalogues in south africa
american portrait painter a jacobsen
hotels in patagonia
but seriously folks joe walsh
address of lima polo club
william butler yeats home address
another instance of voice platform genesys
bonney m stille nacht
former french canadian provinces
creole echoes excerpt
seekingxxx.net
gods goddesses
100 reason stop smoking
all-about-style.com
andre d sparks
map of the westward expansion
examples of meta search engines
aluminum sliding glass door lock
brattleboro vermont nakedness
2008 norton update problems
betty joyce harrison
panasonic.net
7th grade science dothan al
clearwatertribune.com
age of consent in nc
nineteenth century cultural stereotypes
smt contract manufacturing at elgin il
20mn.com
avian immune
arresting or reversing foot neuropathy
citalopram actavis pirist v l ke
netinfo.bg
1929 cadillac imperial
mikesradioworld.com
anatomical mold
12 days of christmas gift ideas
asx-200bx lan
gaydadsandyoungersons.com
isabella fiore let love reign purse
allow interactive logon to workstations
computer sent received meter
amicroe ready boost usb drive
augustinespiritualgoods.com
basilica di bologna
cj fitzgerald
chicks in sturgis
buenos aires art supplies
password protect folder sme server
australia port fairy accomodation
chantal hensley
ariston dishwasher
2009 liturgical year
soundproofwindows.com
absent cells on pap
gold rush miners in california 1852
content for newsletters
academy countdown leader
craaigslist.com
air race reno 2007
pdfsoftwarecenter.com
desert crepes
battlefield 1942 home page
assignments on employee made by organisations
a taste of thai instant meals
custom stainless products etobicoke ontario
a w d hammond ltd website
frcp exemptions
albums released in 1989
2wire router problem wii
amanda marie gould
greek writing utensils
child abuse coppell texas
snappysoftware.com
jillian barberi
keeler hydraulics
install fedora on mac powerbook g4
exoticagirls.com
cakewalk music creator crossfader
cats beta carotene treat tylenol toxicity
norterrashopping.com
american culinary wagner ware wholesale
belinda jensen autobiography
ben hogan golf tips
concave and convex
antelope complex fires in the west
alan dresner and natalie
bluetooth setting cingular t616
adolf hitlars childhood
endorsement for your friend
artificial intelligence checkers
albright on ot phoenicians
label stuck in tde laminator
aimpoint style reflex sight
brook skye video
contemporary perspectives in writing
acmediy.com
franconia sami fakhouri
custom shower curtains with longer lengths
sacramentorealestatevoice.com
express scribe dss problems
air travel carry on rules
abraham lincoln association
bilingual baptist minister indianapolis in
atomic absorption spectrometry free book welz
bacon club t-shirt at journeys
1700 hemlock oxnard
a little pain tabs nana
40th birthday rhymes
ahadees.com
brookside equestrian centre kitchener
adanal roofing langley bc
h clinton supporters
burning crusade
1760 59th avenue sacramento ca 95822
atkins beach diet south vs
bible xml
elder david pennington
1903 legare circular sock machine
asparagus baked wine
1911 22 rimfire conversions
191 2nd avenue cochrane ontario
agatha christie novels online
american pledge
bellcad.org
circut city rebates
crater lake green outcropping
condos townhouses new bern nc
download stairway to heaven
bed robe
adobe epic app cannot be launched
11x17 4c process preliminary poster examples
daytime emmy award talk show
burley samba
char-broil rotisserie
adoro las es liebe sein
homosexuality umass amherst
100 cc suzuki sv
birch carrol cinema townsville
1973 firebird radiator support
sandia memory gardens
probeindustries.com
fumani dialect
nacelink.com
avalon title ltd mclean virginia
farwestfamilyservices.com
antwerp cut diamonds
dino van eeckhaut cairo appointed sofitel
dosha.org
2008 sport touring
bleeding doge truck breaks
johnnycrosslin.com
24071 desert drive florence az 85232
bioclusive overlay
areas effected in 2007-2012
geography hottest part of the world
aikenregional.com
antarctic centre new zealand shop
coupons for amazon purchases
add affiliate link program
alicia keys samsonite man
saltlaketribune.com
accessory lady
aboutlilacs.com
banner insurance rockville md
elvi fashion stockists uk
federal govt
nalco.com
ankle fracture lower extremity
beloved sisters mc
alisha lanier
cindy ziegler re max of wasilla
32 degrees mesa watch
beat the clickbank competitors
audi a4 fuse changing
adjusting bernina 1001 bobbin tension
australian olympics bike riders
cheap las vagas limos
pulmicortrespules.com
1611 bosch power tool parts breakdown
12 ci engine hp
articles about human resource managment
cal state university pomona anthropology
buses into motorhomes
international tae kwan do karate federation
ana and muscle antibody
dav pilkey biogrpahy
12 week old boxer puppy photos
5 interesting facts about scallops
darnell crisconi
foxfire banjo
4gazebos.com
research terrestrial orchids
cloudster.com
allergic reaction to dust
hickoryortho.com
lexis nexus herb
milky cat torrent
comprehensive-kidney-facts.com
b strep symptoms
07 ford mustang gt
waterfrontbluesfest.com
antique wardrobe trunk pricing
banana fana fo fana
856 edi invoice