Conditional Statements 3

if ( ... ) { ... }  else ( ... ) { ... }

A if / else if construction provides a list of conditions that are mapped to a specific statement block. The conditions are precise--they must evaluate to true--or the statement will not be executed.

However, frequently you cannot or don't want to specify a condition precisely. For example, you want to filter one particular item from a list that can contain anything. An if statement allows you to specify the item you are looking for, but will you do with the rest (provided you want to do something with it)?

One solution is to use the if / else if construction, test for the desired condition in the if statement and for the inverse condition in the else if condition:

   if (x == item)
   {
       take it;
   }
   else if (x != item)
   {
       put it away in a safe place;
   }

The first condition tests for true, the second for not true.

However, computer programmers are lazy when it comes to typing, and there is another construction that accommodates situations like this with less typing: if / else.

   if (x == item)
   {
       take it;
   }
   else
   {
       put it away in a safe place;
   }

else will catch any condition that is not met by if.

else also terminates a conditional block. Any number of else if statements may be inserted between if and else. If no if / else if condition evaluates to true, else will be executed and terminate the conditional block.

   if (item == money)
   {
       take it;
   }
   else (item == food)
   {
       eat it;
   }
      else
   {
       put it away in a safe place;
   }
   
   (continue with script)