Next freebie in 28 Hours*
Suppose we have a scenario where we need to perform some operations when a condition is true in real life, and also alternative backup actions if the condition fails.
That is, a single condition is still tested, but there is a “default” alternative action , or actions, which is/are executed when the tested condition evaluates to false.
Consider, for example, a query posted to a fan of famous Canadian musicians. Suppose the fan is asked about her favorite single, either by a male or a female musician.The logic employed by one particular fan would look like the following pseudo-code:
var isMale:boolean = false;
var maleSinger:string = “”;
var femaleSinger : string = “”;
//populate isMale using some logic
maleSinger = “Bryan Adams”;
trace(“18 Till I Die!”);
femaleSinger = “Celine Dion”;
trace(“My Heart Will Go On!”);
Note that exactly one of the two clauses, the “if” and the “else” get executed for any single execution of the above code. This behavior can be described as “Mutually Exclusive.” Both are never executed in a single run of this single program. Based on what value is stored in the boolean isMale, different executions of the same code could yield any 1 of the 2 intended results.
Also please note that we have used curly braces in the if and the else clauses, since each clause allows for execution of compound (multiple) statements, based on the conditional value. The rules and the expected behavior that we discussed with compound statements and curly braces for a “if” clause, apply for the “else” clause as well.
As we shall see later when we discuss “nested if clauses,” there can be further testing of conditions within an “else clause.” Such a structure would be best described later in the course, so as not to confuse beginners
Have a question but don't want to ask it publicly? If you are a prime member just ask right here and we will get back to you within 48 hours. Not prime yet? no worries you can ask publicly below.