AS3 Basics: If Statements

Ok so after about a month of Alan nagging me to post something,  i’ve decided to write more about the core basics of the AS3 Language, Mainly because my previous “AS3 Basics” tutorials actually covered advanced topics. So each week i’ve set myself the task of explaining a core AS3 element, be it a class or language basics.

IF Statements

So if your just starting out in programming and AS3 then you will very quickly start to see things such as:

if(myNum == 1)
{
    myNum = 2;
}

Written in words this means “If myNum equals 1 then make myNum equal 2″.

Here i’ve added comments to my code to show you where things are happening:

if(myNum == 1) // If myNum equals 1
{ // then
    myNum = 2; // make myNum into equal 2
}

This its whats known as a conditional statement, It evaluates 2 or more expressions using the chosen operator (“==” in this case) you chose to use.

For instance our current one checks to see if the variable “myNum” is equal to “1″.

Here is an excerpt from the Adobe livedocs on Operators:

== equality Tests two expressions for equality.
> greater than Compares two expressions and determines whether expression1 is greater than expression2; if it is, the result is true.
>= greater than or equal to Compares two expressions and determines whether expression1 is greater than or equal to expression2 (true) or expression1 is less than expression2 (false).
!= inequality Tests for the exact opposite of the equality (==) operator.
< less than Compares two expressions and determines whether expression1 is less than expression2; if so, the result is true.
<= less than or equal to Compares two expressions and determines whether expression1 is less than or equal to expression2; if it is, the result is true.

As you can see there are many operators that allow you to perform many different comparisons.

If statments can be expanded by using “else”:

if(myNum == 1)
{
    myNum = 2;
}
else
{
    myNum = 1;
}

Written as a sentace its kinda like this “If myNum equals 1 then make myNum equal 2 otherwise make myNum equal 1″.

You can also string together if statments like so:

if(myNum == 1)
{
    myNum = 2;
}
else if(myNum == 5)
{
    myNum = 10;
}

Written as a sentance would be like so “If myNum equals 1 then make myNum equal 2 otherwise if myNum equals 5 then make myNum equal 10″.

In Addition you can write IF statements in shorthand to save on space. Personally i like to have mine well structured, however shorthand is usefull to keep file sizes down and such.

if(myNum == 1)
{
    myNum = 2;
}

This can be written in shorthand like so:

if(myNum == 1)
    myNum = 2;

This only works when an IF statement contains only one instruction (things with ; at the end).

also an IF ELSE statement can be written shorthand:

if(myNum == 1)
    myNum = 2;
else
    myNum = 1;

I hope this has been helpfull, if you have any questions or additions drop me a comment!

Peace out

Bill

Tags: , , , , ,