Home

ABCs of Programming Constructs

Condition Containers

A Conditional Statement is responsible for "making decision" on what to do next in the code. It is used to control the flow of a program.

A. If Statements

Syntax:

if(condition  evaluate to true)
{
Add code to do something here…
}

ONE IF STATEMENT

If a SINGLE IF statement is used, then the condition will be check to see if it is true, and if so, the code block will be executed. Otherwise, the code block will be ignored and processing will continue on the next line. Hence, an if statement acts as an on/off SWITCH for your code. In fact, you will see later, a construct called a SWITCH statement that can be used as a alternative to using multiple if statements.

EXAMPLE:

var isRaining = true;
 if (isRaining == true)
  {
   alert ("Bring an umbrella");
 }
NOTE: The variable isRaining is not part of the if statement. It is used to provide a condition for the if statement to met.

The result will be the phrase "Bring an umbrella" because the variable isRaining is set to true. If the condition was not true (by changing the variable isRaining to false), the entire code block between the curly braces ({.....}) will be skipped over (ignored).

The condition "isRaining == true" basically is saying "Compare isRaining to the value true." And if it is indeed true, execute the code block.

CAUTION: Note you need to used a double equal sign (==) which is a COMPARISON operator and not an ASSIGNMENT operation which is the case with a single (=) equal sign in the variable. If you use a single equal sign (=) in a loop, the loop will always resolve to true and you will have created an endless loop which may lock up your system.

IMPORTANT NOTE: If the condition is a Boolean, then you can drop the "== true" part of the condition because a condition is ALWAYS IMPLIED to be true initially. While a Boolean may evaluates to true and false by nature, any expression that evaluates to true or false can be used in an if clause with the "== true" dropped:

var isRaining = true;
 {
 alert ("Bring an umbrella");
 }
Again, the result will be the phrase "Bring an umbrella." If the condition was not true, the entire block will be ignored.

NOTE: A condition will evaluate to true if it is NOT FALSE, 0, NULL, or and empty sting (" "). To check for the presence of these values (FALSE, 0, NULL and empty string) or if the variable has not be set at all, use the NOT operator (!) which is an exclamation point:

if (!login)
 {
   alert("You must login in first.");
 }
NOTE: It is important to note that if the variable login is not in the code anywhere which mean that it does not exist, the variable will resolve to TRUE because it is not set. However, the NOT operator will set it to FALSE.

IMPORTANT NOTES:
1. A variable with a number data type will evaluated to true if it is not null or zero (e.g., if(numeralVariable) ); otherwise, it will be false.
2. A String, an array, or a complex data type will evaluate to true is it is not empty or null. For example, an object will be true if it exists with that name and was not explicily coded to null (e.g., myObject = null). ?????

Other common comparison operators includes:
1. > – greater than
2. < – less than
3. <= – greater than or equal to
4. >-= – less than or equal to
5. != – not equal to (not to be confused with ! by itself without an equal sign which will reverse a condition and is use to create a "toggle" effect.
6. === – strict equal to compares not only the VALUES but the TYPE of value (e.g., "2"==2 is true; but "2" === 2 is false because while the value for both two (2), the types are not). There are other type of strict operator (e.g., !==), Care should be made when using strict equal in form element (e.g., JavaScript) because form elements are ALWAYS strings even though a user enters a number.

LIST OF OPERATORS (pg 130 of PHP book)

MULTIPLE IF STATEMENTS

When using multiple IF statements, each IF statement is treated separately.

var isRaining = true;
          var isSnowing = true;
 
// Condition 1: ~~~~~~~~~~~~~ 
 if (isRaining)
  {
   alert ("Bring an umbrella");
  }
          
// Condition 2: ~~~~~~~~~~~~~ 
 if (isSnowing)
  {
   alert ("Bring a jacket");
  } 

RESULT: The result will be the phrase "Bring an umbrella" AND "Bring a jacket" because both IF statements are executed separately.

IF STATEMENT WITH MULTIPLE CONDITIONS

You can not only have multiple IF statements but also multiple conditions WITHIN a given IF statement using LOGICAL operators (e.g., and (&&)or ( || ), or (!) not). The not operator can also be used with an equal sign to represent "not equal to."

var isRaining = true;
var isSnowing = true;
          
 if (isRaining && isSnowing)
  {
   alert ("Bring an umbrella AND bring a jacket");
  }    

RESULT: The result is "Bring an umbrella AND bring a jacket."

B. If / Else Statements

IF STATEMENT WITH ELSE/IF STATEMENTS (ADDITIONAL CONDITIONAL ALTERNATIVE TESTS)

You can use multiple IF statements with multiple ELSE statements. The previous example was used and the word ELSE were added before the second and third IF statements. With an IF/ELSE pair, if a condition is met, the IF block is executed. Otherwise, an alternate code block MAY BE executed by the OTHER ELSE statements.

The difference from having multiple IF statements where they all will be executed separately (See previous example), using the ELSE clause will cause ONLY ONE statement to be executed if a condition is found to be true.

var isRaining:Boolean = true; var isSnowing:Boolean = true; var isCold:Boolean = true; if (isRaining) { alert ("Bring an umbrella"); } else if (isSnowing) { alert ("Bring a jacket"); } else if (isCold) { alert ("Bring a coat"); } RESULT: The result "Bring an umbrella" even though the condition isSnowing is true as well.

IMPORTANT NOTE: It is important to note that if you use multiple IF / ELSE statements, it is possible that all of the statements can resolve to true; however, only the FIRST true statement is evaluated. In the previous example, it could be raining, snowing and cold all at the same time. However, only the "Bring an umbrella" will be executed.  If you needed more that one condition to be true at the same time, you can use multiple if statement or use a single if statement with a logical or operation for multiple conditions. (See previous two examples.)

NOTE: The else and if could be written on the same line. However, to see the structure better they are placed on separate lines. Also, in some programming languages, it is written as a single word (e.g., elseif).

IF STATEMENT WITH ELSE BY ITSELF (CONDITIONAL WITH DEFAULT—IF NO CONDITION IS MET)

You can use an optional ELSE statement as a "safety net" to default to if none of the conditional statements are true. In this example, all of the variables are set to false and an else statement was added. Also an else code block was added:

var isRaining = false;
var isSnowing = false; var isCold = false; if (isRaining) { alert ("Bring an umbrella"); } else if (isSnowing) { alert ("Bring a jacket"); } else if (isCold) { alert ("Bring a coat"); } else { alert ("Bring nothing at all"); }

Another example:

var thumbNail = "thumbNail.gif";
// var thumbNail = "thumbNail.tiff"; if (thumbNail.indexOf("jpg") != -1 || thumbNail.indexOf("gif") != -1 || thumbNail.indexOf("png") != -1) { alert("The image is web-friendly"); } else { alert (The image is not a web-based image (e.g., .jpg, .gif, .png); }

NOTE: When using indexOf with a String, a value of -1 means .....

NOTE: It is important to remember that IF a condition is NOT met, the ELSE code block will handle the "default" action regardless of the other if or if/else statements.

NESTED IF STATEMENTS WITH AND WITHOUT AN ELSE

Not to further complicate matter, you can nest multiple if statements so that if the first "if" statement is false the other "if" statements are skipped altogether. It is best practice to indent the nested if statements so that you can see the structure better. The else/if (instead of if/else) allows you to perform multiple comparisons.

var day = "Wednesday";

 if (day == "Friday")
  {
   alert ("I am looking forward to the weekend");
  }
 else
   if (day == "Sunday")
   {
     alert ("I am lookng forward to going to work")
   }
  else 
   if (day == "Wednesday")
   {
    alert ( "It is the middle of the work week")
    }

RESULT: If the day is Friday, the result is "I am looking forward to the weekend" and the other two if statements are skipped altogether becuase the other two if statements are nest inside of the first if statement code block. If the day is not Friday then the other two if statement conditions will be tested for true and if it is Sunday the result will be "I am looking forward to going to work" and if it is Wednesday the result will be "It is the middle of the work week."

NOTE: An optional ELSE statement can be used ONLY ONCE and must be at the end of the if/else list of statements and does NOT have a condition (test). You can have multiple else/if clauses but they must appear AFTER the IF statement and BEFORE the ELSE clause.

A less common if/else statement is called the tri is sometimes used for simple responses. It has an unique syntax format:

test condition ? true statement : false statement

score > 0 ? alert("play again") : alert("game over");

If you need more than one true or false statement you have to resort to the regular if/else statement.



C. Switch Statements

SWITCH STATEMENT—ALTERNATIVE FOR MULTIPLE IF STATEMENTS

If you intend to use multiple IF or IF/ELSE statements, you can simplify the code by using a SWITCH statement instead. Unlike the IF statement the SWITCH statement will evaluate any condition even if it is false.

  • The break keyword is used to break out of the statement.
  • The default keyword is akin to the else statement which is the default if none of the statements are met. The last break is optional but used for consistency.

The switch statement allows you to control which results are executed even when a test evaluates to false and can allow multple results.

The switch syntax begins with the keyword switch follow by the variable that needs to be tested in parenthesis. Then a code block with a series of case statements. Each case statement contain the value in which the variable will be compared. If they are equal, the statements following the case are executed even if a case is equal to the value being compared it will continue through the rest of the case statements. To prevent this from happening, a break clause can be included with each case statement that with "break" out of the switch.  

The switch statement can also include a default case (similiar to the if's else clause). It will execute if none of the other cases match.

The main disadvantages of the switch statements is that it can only test for equality and only against a single variable. If you need any of these options, you will have to use the if statement with if/else clauses.

A switch is useful when you have a RANGE OF SET VALUES that you want to check:

// var weather = "isRaining";
var weather = "isSnowing";
// var weather = "isCold";
// var weather = "isSunny";
   
switch (weather)
 {
  case "isRaining":
  alert ("Bring an umbrella");
  break;

  case "isSnowing":
  alert ("Bring a jacket");
  break;

  case "isCold": 
  alert ("Bring a coat");
  break;
 
  default:
  alert ("Bring nothing at all");
  break;
 }

RESULT: The result will be the phrase "Bring a jacket" in the because the weather variable is set to "isSnowing" and the other three variables are commented out. If you select "isSunny", the result will be "Bring nothing at all." It is important that you have a variable that can be tested against. For example, if you did not have the var weather = "isSunday" then the result would be nothing not "Bring nothing at all"

NOTE: The switch statement is particurily useful with the break key word when you want to perform the SAME ACTION for MULTIPLE cases:

var currentMonth = (new Date().getMonth()+1);
 switch (currentMonth) 
 {
  case 1:
  case 2:
  case 3:
  default:
   alert("This is the First Quarter of the Year.");
  break;
  case 4:
  case 5:
  case 6:
   alert("This is the Second Quarter of the Year.");
  break;
  case 7:
  case 8:
  case 9:
   alert("This is the Third Quarter of the Year.");
  break;
  case 10:
  case 11:
  case 12:
   alert("This is the Fourth Quarter of the Year.");
 break;
 } 

Key points to remember about conditional statements:

  • The statement in parenthesis will always resolve to true or false.
  • You don't have to explicitly state a statement is true if it is a boolean--it is implied. For example, you can write "if(x)" instead of "if(x == true)".
  • To evaluate a statement that is NOT TRUE, use the else clause (not statement).
  • If just the "if" statement is used and the condition is not met (resolve to not true) then the entire if code block is ignored. If the "if and else" statements are used and the condition in the "if" statement is not met, then it default to the "else" clause and execute the alternative code.
  • An if statement is a switch for a code block.
  • It is helpful to think of the if statement as a "truth tester."
< Previous Topic     Next Topic >