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

consumer report on tankless water heaters best-free-movie-porn.com a mouses digestive system how to do needlepoint a needle pulling thread james johnstone joni belfast telegraph newspaper ecchi teacher ova antron compact electronic ballast blackout on a water ride jenniferanistonfakes.com 25 acres arizona christian fitness center smithfield ri uofm.com computer fixer arte contemporaneo excercises for torn rotator cuff sean hannity gun video mozart figaro 17 track moulin rouge cd adultclassified.com bed extenders chantal lemay realtor a separate peace envy capability study template bottle stopper favors caera kirsch marika vigo easylenderonline.com 2008 weight lifting accident andrews-products.com free synonym dictionary a robert paris clarinet ceo health investment decisions stargazersrealm.com a reason for handwriting kindergarten babystyle and entrepreneur magazine ana guerra oxnard birth date enya amino carcinoma egyptbeauty.com butler sweatshirt lake oconee shooting club after the lovin midi 1858 remington army revolver current prime intrest rate 3d cartoon index 1895 utah saddle makers 1 4 wall pipe load capacity jonathan sedgwick asus motherboard via chipset earthfaire.com 3dsmax landscape tutorial anders celsius life aon eligible rollover fund battery for dell inspiron 1150 hersheys kisses flower arrangement pakistanchristianpost.com andres vu strawberry 0.02 white cell count after chemotherapy lyrics thats not the airways tradera.com invisible braces orthodontic gresen minneapolis spool valve models 3240 lassen way sacramento ca charles v nickname addon wow search ancestorinfo.com j p sauer serial numbers alex jones interviews amy goodman 1 corinthians 14 33 a4 file manager air curtains fostoria crystal jefferson pattern picture bayer basket polymerizer berita keburukan program akademi fantasia clint eastwood and hillary oil of olay definity product review burnt creek club bismarck nd bestmedsmarket.com burnt hills wrestling tournament 1957 chevy convertible ra.com aboriginal veterans avalanche by arthur roth black and decker wallpaper steamer amy vs kanye 1900 sr maxum boat specs oregongolf.com slightly stoopid aug 4 young-lesbians.us cindy yates guiner lani all natural sausage 35 ah battery attractions in southwestern mn rodserling.com bard air alanon.org.za cannot ping default gateway 50 sodium hydroxide drifting events indiana mybb.ru john laurens hsbc michigan repossession notification law gotshemales.com miniclip m ussecurityassociates.com 1680x1050 images david crowder band tabs presentationexpert.com hurd family origin artists from marine-on-st croix mn accesso maestro beau de jour comevisit.com dj alex hidalgo mp3 shared files analyst notebook excel sanborn air compressors female gender representation in films audio mixing in the 1960s alabama state congressmen kcu.edu free outrageous funny weird photos bridgette elaine gaillot citi bank financial 4 seasons travel puerto rico berry athletic stadium cypress dungeons and dragons 3rd 1957 chevy alternator conversion desperate bad credit personal loan inter.co.yu accident steam cleaners inc alan charles clark said black and decker 4300 charity donate veterans thrift store phoenix blackberry muffins abba eurovision cheats for ratchet dead locked disable driver signing in vista x64 interior taj mahal auto fidelity finance bird buffer fabry-perot resonator celine cousteau flax and borage oil 1986 power ram w250 equator hidden fastener cath mersh gestational sac debris calphalon hard anodized cookware 1971 jimi hendrix passes bradley van ness mini-itx mainboard with hdmi abilene tourism amish 24 inch deacon bench nabe.org splinter blood clots antiphospholipid antibody syndrome north carolina nonresident shareholders identifying number lago como appartamenti vacanze inarng.org christmas in provence compounding pharmacies antarctica continent kids hospicebuffalo.com computadora en la educacion apple iphone news rumors blessed rosary andy warhol ceramic bronze bowl platypus bengals victoria c caribe ge products arecibo cheatcentral.com chaffoteaux maury barrows armour runescape armytents.com courtyard inn tuscaloosa 12-volt ceramic heater www-boxelderbugs.com calloway antique auction sanger texas extend brushes motor operationspringbreak.com abstracts on tea from plants 62 sanchez luis baby boomers the villages fl 19th century clothing reproductions dsp equalizer 1990 suzuki sierra lift kit bars irving texas burglar bars and alabama drkdesyre.com 5.0 hood guage pod air force parent weekend 1,4 dichloral benzene bamboo toothbrush allergy to coal mandarin chinese rowlett texas friendswood isd jobs 410 avenue school winnipeg healthierdogs.com brick oven in sparta tn 303 bullet trajectory brushed nickle fan light mnjobbank.com atv cullman barcelo bavaro santo domingo usedwinnipeg.com apartments in eau claire wi mako amps completed haccp plan training air chuck parkside at ashburn eplaymates.us britax boulevard in mosaic fixing lag on pc gaming amie dworecki cross functional decisions definition internetdatabases.com .22 rifle sales american woman heather graham build a bulkhead bangkok thai lacey wa bible marriage poems foe wedding couple 2000 election overseas vote zepka.com chronic ventricular fibrilation athens to rhodes flight eyewearmagic.com 1987 ferrari testarosa civil war colt revolvers antecedent behavior consequences expanded program immunization american trail riders association abingdon meat packers the fight over zac efron camp rock jonas brothers games california health care providers preferred choice chicken orange marmalade wild rice hon 3 drawer lateral file abc distributions company baton wall supports and studs cribbage score on paper showmeminitrucks.com augustus medlin jr section 202 wr ga abbott and costello bioraphy making popsicle stick dog sleds csmp.org ar-15 breakdown guide boy scout saves politician animated gifs for your email doi.org bill steele land art 3d tic tac toe instrucions john deere roto tiller hearst castle pictures decaf teas colombo baking co controled insanity burley knit terry 2007 updos hairstyles yokohama 235 60r16 avid trz 2.0 carat hearts on fire diamond importateurs chocolat belge cock-pictures.com modena agritourismus estimated cost attic insulation ga blackfoot idaho court house myimagefirst.com colourless deadly gas tarotburbrujas.com alexandria trips and tours planthaven.com detroit hiphop r b artists stepsforpets.com basketball blankets comforters quilts 07e7 listing all things organic conference chinook campground hernandomls.com aerosoles sunbeam sandal biblestoriesforadults.com earth magnitude northridge quake naughtyamateurcinema.com artificial reef coral decorative boundaries divorce relationships and jealousy agence de positionnement blueridgeimpressions.net compaq monitor presario mv700 user guide j renee lorraine jocelyn goldring woldenberg hall tulane southpark 2008 13 the movie free on line stargate gaming azo dye prohibition samuel paul thierry bmw m5 twinscrew supercharged kit invision power board ipb button 5 gallon mini bow ann fagelson government seminars christmas cactus blossoms nvisible.com 3d apple themes calm hyper dog havoc boxing discount expresso machines beanstreamcarts.com 2004 tacoma factory alarm cap tel telephones hard of hearing advest boca raton fl 2001 cost of living cortisone knee shots 1stophomebuyer.com brian levine carolina access enrollment form medicaid healthcare tenders dai vernon signed buy short-on-cash.com dr john lee benin azalea middle school norfolk va amy macdonald poison prince reviews komkon.org classical guitarist 12-15 girl photos john atchison child solicitation ac power adapter to cigarette lighter 13th anniversary show business card upload jacobsen architect giftscandle.com bean bag lap desk with light cibc banks toronto 3-d wooden sign 503 n oakland carbondale average daily temperatures new york melissa ursula dawn goldsmith november 2006 ubs aluminum foil dissolution with ferrous sulfate crack wall sidewalk drawing or picture imer.com.mx aiken hearing impaired cameron tract parsippany 1985 toyota tercel wagon lean on me bill withers lyrics what is hyaluronic acid collaborative change chiropractic subacromial bursitis classmate locater