Conditional branching
Conditional branching is a very important part of programming because it will allow your program to behave differently depending on the context. So, let's talk about if
and switch
.
If
The if
expression allows you to test an expression; if it returns true
then the following expression will be executed. You may also use the else
keyword, followed by an expression, which will be executed if the test returns false
. Note that a block of code is an expression.
The following is the general syntax:
if (condition) exprExecutedIfTrue [else exprExecutedIfTestFalse]
Now, let's look at some examples:
if(age<18) { trace("you are not an adult."); } else { trace("You are an adult"); }
I think it is obvious here what this block of code does. Notice that this code could have been written in the following way too:
if(age<18) trace("you are not an adult."); else trace("You are an adult");
This can be interesting to know, as it can save some typing when the block has only one...