Not yet rated

Problem

What's the best way to use if and else?

Solution

Use if, if..else if, and if..else if..else

Detailed explanation

Some programming languages use if..then statements, but ActionScript uses if..else. It's the same construction. Use if to test for a particular value or case and then branch your response according to the value.

For example, you can test whether a variable is a certain value: if it is, do one thing; if not, do something else. You can also test for more than one value using else if as many times as you want. This statement works for both ActionScript 2 and ActionScript 3.

Test for values equal to 5 or 6; if neither, say so:

var value:Number = 5;

Notice that we need to use == (double equal sign) to test for equality:

if(value == 5) {

   trace("value is 5");

}

else if(value == 6) {

   trace("value is 6");

}

else {

   trace("value is neither 5 nor 6");

}

If you just want to see whether the value is 5 and don't want to do anything else, you can use an if statement alone:

var value:Number = 5;



if(value == 5) {

        trace("value is 5");

}

If the value is 5, the trace statement is executed; otherwise, nothing happens.

Note: You can also use the case..break construction to test for a specific set of values.

 

Recipe originally contributed by Mike Chambers.
Recipe updated by Dave Jacowitz.


+
This work is licensed under a Creative Commons Attribution-Noncommercial-Share Alike 3.0 Unported License. Permissions beyond the scope of this license, pertaining to the examples of code included within this work are available at Adobe.

Report abuse

Related recipes