Team LiB
Previous Section Next Section

Chapter 2: Selection and Repetition Statements

This chapter covers two of the most important features of the JavaScript language, selection and repetition statements. Normally, statements in a program are executed sequentially, in the order that they were written. Often it is useful to transfer control in the middle of execution to another section of code—sort of like changing trains at the terminal. The transfer might be just a couple lines of code away, as is the case with loops, or might be a different block of code all together, which is what selection statements do. So that you can accomplish this, several statements that alter the sequential flow of a program are included in the JavaScript programming language. Together, selection and repetition statements are known as control structures.

Selection Statements

Selection statements are the decision-making control structure in JavaScript; they are used to choose among alternative courses of action. A program would not be useful at all if it did the same thing no matter what the conditions were while it was running. Selection statements are very easy to translate from English into JavaScript and back again.

Using if and if-else if Statements

Selection statements are your basic decision-making statements in JavaScript. The if structure is the single most used selection statement in the JavaScript language. The syntax of the if statement is as follows:

if( <condition> ){ <statements> }

The condition part of the statement can be any statement or relational operator that returns a boolean value. The statements inside the brackets will be executed only if the condition evaluates to true. As I stated earlier, selection statements are easily translated to and from English statements. The following statement:

If theVar is greater than 2
  Set theVar equal to 1.

determines whether the variable theVar is greater than 2. If it is, then assign the value 1 to it. This English sentence can be literally translated into the following JavaScript statement:

if( theVar > 2 )
{
  theVar = 1;
}

This example would have a practical purpose if you were trying to create a table with rows that have alternating colors. The full function might be the following:

<html>
  
  <head>
    <title>
      JavaScript Professional Projects - Selection Statements - if/else
    </title>

    <script language="JavaScript">
    <!--
      var rowNumber = 1;
      function getColor()
    {
      var color;
      if( rowNumber > 2 )
      {
        rowNumber = 1;
      }
      if( rowNumber == 1 )
      {
        color = "gray";
      {
      else
      }
        color = "white";
      }
      rowNumber++;
      return( color );
    }
    // -->
    </script>

 </head>

 <body>

   <center>
     <font size=6>JavaScript Professional Projects</font><br>
     <font size=4>Chapter 2: Selection Statements - if/else</font>
   </center>

   <br><br>

   <p>
     <table width="85%" border="1">
       <script language="JavaScript">
       <!--
         document.write( "<tr bgcolor='" + getColor() + "'>" );
       // -->
       </script>
         <td>&nbsp;</td>
         <td>&nbsp;</td>
       </tr> <script language="JavaScript">
       <!--
         document.write( "<tr bgcolor='" + getColor() + "'>" );
       // -->
       </script>
         <td>&nbsp;</td>
         <td>&nbsp;</td>
       </tr>
       <script language="JavaScript">
       <!--
         document.write( "<tr bgcolor='" + getColor() + "'>" );
       // -->
       </script>
         <td>&nbsp;</td>
         <td>&nbsp;</td>
       </tr>
       <script language="JavaScript">
       <!--
         document.write( "<tr bgcolor='" + getColor() + "'>" );
       // -->
       </script>
         <td>&nbsp;</td>
         <td>&nbsp;</td>
       </tr>
       <script language="JavaScript">
       <!--
         document.write( "<tr bgcolor='" + getColor() + "'>" );
       // -->
       </script>
         <td>&nbsp;</td>
         <td>&nbsp;</td>
       </tr>
     </table>
     </p>
   </body>
</html>

This very simple code creates a table with two columns and five rows. The odd-numbered rows have a background color of "gray" and the even-numbered rows have a background color of "white". The technique of alternating row colors could be very useful if you are displaying a lot of data in a table because it makes the individual rows easier to distinguish.

You'll notice that in the function there is a regular if statement, like in the original example, but then there is an if statement with an else attached to it. The statements contained within the else block will be executed only when the condition in the preceding if is determined to be false. In the preceding example, the if statement will run when rowNumber is equal to 1, and at all other times the else statement will be run. The syntax for the if/else structure is

if( <condition> ){ <statements> }
else{ <statements> }

That is not the end of the story with if statements, however. If you have a lot of conditions that you wanted to check and you want only one block of code run for each one, you may end up doing something like the following which prints a grade letter based on a given score:

if( n >= 90 )
{
  document.write( "A" );
}
else
{
  if( n >= 80 )
  {
    document.write( "B" );
  }
  else
  {
    if( n >= 70 )
    {
      document.write( "C" );
    }
    else
    {
      if( n >= 60 )
      {
        document.write( "D" );
      }
      else
      {
        document.write( "F" );
      }
    }
  }
}

If n is greater or equal to 90, then the first four conditions will be evaluated to be true, but only the letter A will be displayed. After the first condition is evaluated to be true, the else attached to it will be skipped. This is a perfectly legal way to check for multiple conditions. It does, however, result in deep indentations that can be hard to read. Many programmers prefer to write the preceding if structure as:

if( n >= 90 )
{
  document.write( "A" );
}
else if( n >= 80 )
{
  document.write( "B" );
}
else if( n >= 70 )
{
  document.write( "C" );
}
else if( n >= 60 )
{
  document.write( "D" );
}
else
{
  document.write( "F" );
}

The two forms behave in exactly the same way. On average, the nested if/else statements in the first form can run faster than the series of if/else if statements in the second form. To increase the runtime of your programs, test the conditions that have a greater chance of evaluating to true early; doing so will cause the structure to exit earlier.

The complete syntax for if/else if/else structures is as follows:

if( <condition> ){ <statements> }
else if( <condition> ){ <statements> }
...
else{ <statements> }

To avoid extra characters in the source file—which increase download time—omit the curly braces surrounding a single statement in an if structure. The second form in the example above could be rewritten as

if( n >= 90 )
  document.write( "A" );
else if( n >= 80 )
  document.write( "B" );
else if( n >= 70 )
  document.write( "C" );
else if( n >= 60 )
  document.write( "D" );
else
  document.write( "F" );

This is an overall more compact, but slightly harder to read, version that accomplishes the same goal. When omitting braces, it is important to understand how the else statement matches up with preceding if statements. For example, the following piece of code might not do what you would expect:

if( n > 0 )

  if( n < 10 )
    document.write( "n is > 0 but < 10" );

else
  document.write( "n is <= 0" );

This is a perfectly legal if structure. If n is 8, then "n is > 0 but < 10" is output. But what happens when n is 11? You might expect that nothing will be output, but that is not the case. The message "n is <= 0" is output when n is 11—but that is obviously not accurate. What happens is that the else statement is really attached to the inner if statement. This is another case in which not formatting your code correctly may confuse the reader. The JavaScript interpreter in your browser does not know that the else statement was supposed to go with the first if statement. All that the interpreter knows is that there is an if statement followed by another if statement and an else. Its natural response is to connect the else with the if statement that immediately preceded it. To avoid this problem, you will need to be more specific and use curly braces. A better version of the same code would be as follows:

if( n > 0 )
{

  if( n < 10 )
    document.write( "n is > 0 but < 10" );
}
else
  document.write( "n is <= 0" );

This code does exactly what you would expect it to do. When n is equal to 11, nothing is displayed, and when n is less than or equal to 0, the message "n is <= 0" is displayed.

Using the Ternary Operator in Lieu of if Statements

As I mentioned in Chapter 1, the ternary operator can be used to replace simple if/else structures. In the alternating row color example given previously, the if/else structure,

          if( rowNumber == 1 )
          {
          color = "gray";
          }
          else
          {
          color = "white";
          }

can be replaced by the single line of code:

color = ( rowNumber == 1 ? "gray" : "white" );

This, of course, is a little harder to read, but it will decrease the overall download time of your Web page. The revised function,

          var rowNumber = 1;
          function getColor()
          {
            var color;
          if( rowNumber > 2 ) rowNumber = 1;

          color = ( rowNumber == 1 ? "gray" : "white" );

          rowNumber++;
          return( color );
        }

can be simplified even further with the use of the modulus operator. As you learned in Chapter 1, the modulus operator, %, returns the remainder that results from integer division. Keeping this in mind, the entire function could be rewritten as a single line function:

          var rowNumber = 0;
          function getColor()
          {
            return( rowNumber++ % 2 == 0 ? "gray" : "white" );
          }

This trades readability for overall speed.

You could even replace the nested if/else structure above what was used to print grade letters with the following nested ternary operators:

document.write
( n >= 90 ? "A" :
  ( n >= 80 ? "B" :
    ( n >= 70 ? "C" :
      ( n >= 60 ? "D" : "F" )

    )
  )
);

This results in a singe statement that is very hard to read, but it reduces the number of character required to download from 168 to 66.

Using switch Statements

Switch statements are the other selection structure that is supported by JavaScript. While you can replace a switch statement with an if/else if/else statement in any instance, they are not interchangeable—you cannot replace all if/else if/else statements with switch statements. This means that the Switch structure is slightly less powerful, but no less useful. Switch statements are used primarily for comparing a handful of values to a variable that contains a primitive value.

Occasionally, an algorithm will test a single variable against a list of different values and execute separate commands depending on the variable's value. An example of this might be

if( n == 0 )
{
  document.write( "zero" );
}
else if( n == 12 )
{
  document.write( "One dozen" );
}
else if( n == 13 )
{
  document.write( "Baker's dozen" );
}
else
{ 
  document.write( "Some number" );
}

This checks three different values for n, but is a rather lengthy way of testing for three simple values. An alternative would be to use a switch statement:

switch( n )
{
  case 0:
    document.write( "zero" );
    break;
  case 12:
    document.write( "One dozen" );
    break;
  case 13:
    document.write( "Baker's dozen" );
    break;
  default:
    document.write( "Some number" );
    break;
}

The switch structure is made up of a series of case labels and an optional default case.

Each case consists of one or more statements followed by an optional break statement. The complete syntax for the switch statement is as follows:

switch( <variable> )
{
  case <possible value>:
    <statements>
    break;
  case <possible value>:
    <statements>
    break;
  ...
  default:
    <statements>
    break;
  }

There really is no advantage of using a switch statement instead of an if/else if/else structure if both are suitable for a situation. As a rule of thumb, use a switch statement when you are comparing a list of values against a single variable and an if/else if/else structure all other times.

Let's expand on our alternating row color example given previously. If you wanted to use more than two colors in your table, then that would be an excellent time to use a switch statement. Here is an example:

<html>

  <head>
    <title>
      JavaScript Professional Projects - Selection Statements - switch 
    </title>

    <script language="JavaScript">
    <!--
      var rowNumber = 0;
      function getColor()
      { 
        var color;

        switch( rowNumber )
        {
          case 0:
            color = "gray";
            break;
          case 1:
            color = "white";
            break;
          case 2:
            color = "blue";
            break;
          case 3:
            color = "green";
            break;
          case 4:
            color = "red";
            break;
        }
        rowNumber = ( rowNumber + 1 ) % 5;
        return( color );
      }
    // -->
    </script>

  </head>

  <body>

    <center>
      <font size=6>JavaScript Professional Projects</font><br>
      <font size=4>Chapter 2: Selection Statements - switch</font>
    </center>

    <br><br>

    <p>
      <table width="85%" border="1">
         <script language="JavaScript">
         <!--
           document.write( "<tr bgcolor='" + getColor() + "'>" );
         // -->
         </script>
           <td>&nbsp;</td>
           <td>&nbsp;</td>
         </tr>
         <script language="JavaScript">
         <!--
           document.write( "<tr bgcolor='" + getColor() + "'>" );
         // -->
         </script>
           <td>&nbsp;</td>
           <td>&nbsp;</td>
         </tr>
         <script language="JavaScript">
         <!--
           document.write( "<tr bgcolor='" + getColor() + "'>" );
         // -->
         </script>
           <td>&nbsp;</td>
           <td>&nbsp;</td>
         </tr>
         <script language="JavaScript">
         <!--
           document.write( "<tr bgcolor='" + getColor() + "'>" );
         // -->
         </script>
           <td>&nbsp;</td>
           <td>&nbsp;</td>
         </tr>
         <script language="JavaScript">
         <!--
           document.write( "<tr bgcolor='" + getColor() + "'>" );
         // -->
         </script>
           <td>&nbsp;</td>
           <td>&nbsp;</td>
         </tr>
       </table>
     </p>

  </body>

</html>

This example is identical in functionality to the previous example, except that it allows you to alternate between five different colors instead of two.

Another example of where switch statements are a logical choice is when determining the postscript for a number. For example: 1st, 2nd, 3rd, 4th, and so on. This could be useful if you are designing a calendar that displays the number for each day of the month. For now, here is a slightly simpler example:

<html>

  <head>
   <title>
     JavaScript Professional Projects - Selection Statements - switch
   </title>

   <script language="JavaScript">
   <!--
     function getEnding( number )
     {
       switch( number % 10 )
       {
         case 0:
         case 4:
         case 5:
         case 6:
         case 7:
         case 8:
         case 9:
           return( "th" );
         case 1:
           return( "st" );
         case 2:
           return( "nd" );
         case 3:
           return( "rd" );
       }
     }
   // -->
   </script>

 </head>

 <body>
   <center>
     <font size=6>JavaScript Professional Projects</font><br>
     <font size=4>Chapter 2: Selection Statements - switch</font>
   </center>

   <br><br>
   <p>
     <table width="85%" border="1">
       <tr>
         <td>1
           <script language="JavaScript">
           <!--
             document.write( getEnding( 1 ) );
           // -->
           </script>
         </td>
       </tr>
       <tr>
         <td>2
           <script language="JavaScript">
           <!--
             document.write( getEnding( 2 ) );
           // -->
           </script>
         </td>
       </tr>
       <tr>
         <td>3
           <script language="JavaScript">
           <!--
             document.write( getEnding( 3 ) );
           // -->
           </script>
         </td>
       </tr>
       <tr>
         <td>4
           <script language="JavaScript">
           <!--
             document.write( getEnding( 4 ) );
           // -->
           </script>
         </td>
       </tr>
       <tr>
         <td>5
           <script language="JavaScript">
           <!--
             document.write( getEnding( 5 ) );
           // -->
           </script>
         </td>
       </tr>
     </table>
   </p>

 </body>

</html>

This example is an oversimplification of the true power of the getEnding() function, which will be explored fully later on.

There are two peculiar things about the example just given. First of all, there are six case labels in a row that do not have any break or return associated with them. Because they don't have a break statement, the empty case labels all share the statements in the following case statement—in this case, return( "th" );. The second interesting part of the example is the total lack of break statements. Normally, without a break statement, every statement in each case label would be executed until the end of the switch block was reached. In the example just given, the return statements do the job of the break statement by "breaking" out of the switch block.

The importance of the break statement, or in the previous example return statements, cannot be over emphasized. The following example illustrates what would happen if the break statements were left out of the switch structure.

function func( n )
{
  switch( n )
  {
    case 1:
      document.write( "One<br>" );
    case 2:
      document.write( "Two<br>" );
    case 3:
      document.write( "Three<br>" );
    case 4:
      document.write( "Four<br>" );
    case 5:
      document.write( "Five<br>" );
    default:
      document.write( "Some number<br>" );
  }
}

The output from this example would not be what the programmer had in mind. If the function were to be called with the number 2 as an operand, the output would be

          Two
          Three
          Four
          Five
          Some number

Although sometimes this result might be desirable, most of the time it is not. In the previous example, you might expect the output to only print Two, but because I left off the break statements, it prints Two, Three, Four and Five. In the example that printed the number postscripts, leaving the break statements out was a good thing; in this example it is not.


Team LiB
Previous Section Next Section