Richland College Multimedia Learning Center

JavaScript, jQuery, and React
Home e-Handouts and Assignments Syllabus Resources Student Sites Other Classes RLC Multimedia
Updated 6/19/2020 at 1:55pm

Repetition (Arrays and Loops)


References


Array Review

We saw Arrays in the e-handout "Data Types and Operators". Let's do a brief review of arrays.

Recall that an Array is a set of data represented by a single, indexed variable name.

Arrays are represented in JavaScript by the Array object, which contains a constructor function named Array( ). As with any other object in JavaScript, you create a new Array object with the new keyword, like this:

  var hospitalDepartments = new Array(10);
You should note that the numeric argument to the Array constructor function tells JavaScript how many items will be in the array. This argument is, however, optional. In JavaScript, you can add items (elements) to the array as needed, and JavaScript will automatically adjust the count of elements in the array.

Each item in an array is called an element.

The numbering of elements within JavaScript arrays starts with index number zero (0). You refer to a specific element of a JavaScript array by giving the array name followed by the index number enclosed in square brackets, like this:

  hospitalDepartments[0] = "Anesthesia";
  hospitalDepartments[1] = "Molecular Biology";
  hospitalDepartments[2] = "Neurology";
  hospitalDepartments[3] = "Oncology";
  hospitalDepartments[4] = "Ophthalmology";
  hospitalDepartments[5] = "Otolaryngology";
  hospitalDepartments[6] = "Pediatrics";
  hospitalDepartments[7] = "Psychiatry";
  hospitalDepartments[8] = "Pulmonary Diseases";
  hospitalDepartments[9] = "Radiology";

Once you have assigned a value to an array element, you can, just as with any other variable in JavaScript, change the value later if needed, like this:

  hospitalDepartments[5] = "Prosthetics";

Most programming languages require that all of the elements in an array contain data of the same data type, but JavaScript does not limit you with this requirement. You can mix different data types in JavaScript arrays if you wish.

You can assign values to array elements when you first create the array, like this:

  var hospitalDepartments = new Array ("Anesthesia", "Molecular Biology",
    "Neurology");

The Array object contains various methods that we will not discuss here. But a very useful property of the Array object is the length property. The length property contains a value that tells you how many elements are in the array. For instance, you can display how many elements are in an array like this:

  document.write("There are " + 
    hospitalDepartments.length +
    " departments in this hospital.");


Associative Arrays

There is another form of array indexing in JavaScript, used with an array type called "Associative Arrays". In an associative array, the index is a string instead of a number.

Here is some code that shows how a string can be used as an array index in JavaScript:

<!doctype html>
<html>
<head>
  <meta charset="UTF-8">
  <title>Phone Book Demo</title>
  <link rel="stylesheet" type="text/css" href="Samples.css">
<script type="text/javascript">
    /* <![CDATA[ */
    var phone_book = new Array();
    phone_book["happy"] = "(203) 555-1111";
    phone_book["sleepy"] = "(203) 555-2222";
    phone_book["sneezy"] = "(203) 555-3333";
    phone_book["sleezy"] = "(203) 555-4444";
    phone_book["sneary"] = "(203) 555-5555";
    phone_book["bleary"] = "(203) 555-6666";
    phone_book["tweaked"] = "(203) 555-7777";
    
    function displayNumber(the_phone_book, entry)
    {
      var the_number = the_phone_book[entry];
      document.getElementById("number_box").value = the_number;
    }
    /* ]]> */
  </script>
</head>
<body>
  <div id="mainDiv">
    <h1>The Dwarves of Multimedia Gulch</h1>
    <form name="the_form" action="" method="post">
    <table border="0" cellpadding="5" cellspacing="0">
      <tr>
      <td valign="top"><b>Name:</b></td>
      <td valign="top">
        <select onchange = "displayNumber(phone_book, this.options[this.selectedIndex].value);"
           size="7">
        <option value="happy">Happy</option>
        <option value="sleepy">Sleepy</option>
        <option value="sneezy">Sneezy</option>
        <option value="sleezy">Sleezy</option>
        <option value="sneary">Sneary</option>
        <option value="bleary">Bleary</option>
        <option value="tweaked">Tweaked</option>
        </select>
      </td>
      <td valign="top"><b>Number:</b></td>
      <td valign="top">
        <input type="text" name="number_box" id="number_box" value="" />
      </td>
      </tr>
    </table>
    </form>
  </div>
</body>
</html>
You can see the above code running here.

Please note these points about the above code:

Below is a second example of an associative array. You should note carefully in this example that the length property has a value of 0 in an associative array:

<!doctype html>
<html>
<head>
  <meta charset="UTF-8">
  <link rel="stylesheet" type="text/css" href="Samples.css">
  <title>Test Associative Arrays</title>
</head>

<body>
  <div id="mainDiv">
    <h3 style="text-align:center;">Testing Associative Arrays</h3>
  <script type="text/javascript">
    /* <![CDATA[ */
    var myArray = new Array();

    myArray["one"] = 100;
    myArray["two"] = -1.35;
    myArray["three"] = "Kangaroo";

    for (stuff in myArray)
    {
      document.write("The value for index '" + stuff + "' is " + myArray[stuff] + "<br>");
    }

    document.write("The length property has a value of " + myArray.length);
    /* ]]> */
  </script>
  </div>
</body>
</html>
You can see the above code running here.

Please note these points about the above code:


while Statements

The statements you have worked with so far, like the if statements and the switch statement, run in a linear fashion, top to bottom. If you need to repeat a statement, or a function, or other code sections multiple times, you need to use a loop statement such as a while loop. A loop statement repeatedly runs a statement or code block while a specific condition is true or until a specific condition becomes false.

The while statement is used for repeating a statement or code block as long as a given conditional expression evaluates to true.

The syntax of the while statement looks like this:

  while (conditional expression)
  {
    statement;
    statement;
    ...
  }

Please note these points about the above syntax:

Each repetition of a looping statement is called an iteration.

You must make sure that the conditional expression will eventually evaluate to false. If it does not, you will have created what is called an infinite loop. An infinite loop will never stop looping. You really don't want to do this. If you do mistakenly create such a loop, however, you can usually stop the browser by using the CTRL+ALT+DELETE key combination to open the Windows Task Manager and stop the browser.

Here is a sample of code using a while statement:

<!doctype html>
<html>
<head>
  <meta charset="UTF-8">
  <link rel="stylesheet" type="text/css" href="Samples.css">
  <title>While Loop 1</title>
</head>

<body>
  <div id="mainDiv">
    <script type="text/javascript">
      /* <![CDATA[ */
      var count = 1;
      while (count <= 5)
      {
        document.write(count + "<br/>");
        count++;
      }
      document.write("You have displayed " + (count - 1) + " numbers.");
      /* ]]> */
    </script>
  </div>
</body>
</html>
You can see the above code running here.

Please note these points about the above code:

Another form of the while statement is shown below:

<!doctype html>
<html>
<head>
  <meta charset="UTF-8">
  <link rel="stylesheet" type="text/css" href="Samples.css">
  <title>While Loop 2</title>
</head>

<body>
  <div id="mainDiv">
    <script type="text/javascript">
      /* <![CDATA[ */
      var keepGoing = true;
      while (keepGoing)
      {
        document.write("A line...<br/>");
        keepGoing = confirm("Press OK to keep going, or Cancel to stop");
      }
      /* ]]> */
    </script>
  </div>
</body>
</html>
You can see the above code running here.

Please note these points about the above code:


do...while Statements

The do...while statement executes a statement or group of statements once, then repeats the execution as long as the conditional expression evaluates to true. You should note carefully that the do...while statement always runs its contained statements at least once regardless of the initial value of the conditional expression.

The syntax of the do...while statement looks like this:

  do
  {
    statement;
    statement;
    ...
  }
  while (conditional expression);

Please note these points about the above syntax:

As with the while statement, with the do...while statement you must make sure that the conditional expression will eventually evaluate to false. If it does not, you will have created what is called an infinite loop. An infinite loop will never stop looping. You really don't want to do this. If you do mistakenly create such a loop, however, you can usually stop the browser by using the CTRL+ALT+DELETE key combination to open the Windows Task Manager and stop the browser.

Here is a sample of code using a do...while statement:

<!doctype html>
<html>
<head>
  <meta charset="UTF-8">
  <link rel="stylesheet" type="text/css" href="Samples.css">
  <title>Do While Loop 1</title>
</head>

<body>
  <div id="mainDiv">
    <script type="text/javascript">
      /* <![CDATA[ */
      var count = 1;
      do
      {
        document.write(count + "<br/>");
        count++;
      } while (count <= 5);
      document.write("You have displayed " + (count - 1) + " numbers.");
      /* ]]> */
    </script>
  </div>
</body>
</html>
You can see the above code running here.

Please note these points about the above code:

The difference between while and do...while statements is more clearly seen in the following sample code:

<!doctype html>
<html>
<head>
  <meta charset="UTF-8">
  <link rel="stylesheet" type="text/css" href="Samples.css">
  <title>Do While Loop 2</title>
</head>

<body>
  <div id="mainDiv">
    <script type="text/javascript">
      /* <![CDATA[ */
      var displayNum = prompt("Enter a number", "");
      if ((displayNum == "") || (displayNum == null))
      {
        displayNum = 0;
      }
      
      do
      {
        document.write("The number is " + displayNum + "<br/>");
        displayNum--;
      }
      while (displayNum > 0);
      /* ]]> */
    </script>
  </div>
</body>
</html>
You can see the above code running here.

Please note these points about the above code:


Now, here is another version of the above code, which we modified in class in the Fall 2010 semester. We made these changes:

This is file displayNumStuff.html:

<!doctype html>
<html>
<head>
  <meta charset="UTF-8">
  <link rel="stylesheet" type="text/css" href="Samples.css">
  <title>Do While Loop 2b</title>
</head>

<body>
  <div id="mainDiv">
    <script type="text/javascript">
      /* <![CDATA[ */
      var finalNum;
      var displayNum = prompt("Enter a number", "");
      if ((displayNum == "") || (displayNum == null))
      {
        finalNum = 0;
      }
      else
      {
        finalNum = displayNum;
      }
      
      do
      {
        document.write("The number is " + finalNum + "<br/>");
        finalNum--;
        if (isNaN(finalNum))
        {
          document.write("Oops, it's NaN!");
        }
      }
      while ( finalNum > 0);
      /* ]]> */
    </script>
  </div>
</body>
</html>

You can see the above code running here.


for Statements

The for statement is used to repeat a statement or a series of statements (code block) as long as a condition is true. This should sound familiar to you, since it is basically the same definition as that for a while statement. But in the for statement you can include code to initialize a counter and change its value in the for statement itself, instead of doing so in the code block.

Here is the basic syntax for the for statement:

  for (initialization expression; condition; update statement)
  {
    statement;
    statement;
    ...
  }

Please note these points about the above syntax:

  1. The statement begins with the for keyword.
  2. The three items inside the parentheses are separated by semi-colons.
  3. The initialization expression runs only once, and is run when the for statement is first encountered. Usually this initialization expression creates (declares) a variable that is used as a counter.
  4. The condition (a conditional expression) is evaluated. Usually, this conditional expression checks the value of the variable that was created and initialized in the initialization expression. If the condition is true, the statement(s) in the associated code block are run.
  5. After the statement(s) in the code block are run, the update statement runs, changing the value of the variable that was created and initialized in the initialization expression.
  6. The condition is evaluated again. If the condition is true, the statement(s) in the associated code block are run again.
  7. Steps 5 and 6 continue to run until the condition evaluates to false. Then the for statement ends and any statements following it are run.

Technically, you can omit any of the three parts of the for statement constructor (the part inside the parentheses). But you must include the semi-colons even if you omit any of these three parts. And you must make sure you change the condition somehow in your code block, so you don't create an infinite loop!

Here is a sample of a for statement in action:

<!doctype html>
<html>
<head>
  <meta charset="UTF-8">
  <link rel="stylesheet" type="text/css" href="Samples.css">
  <title>For Loop 1</title>
</head>

<body>
  <div id="mainDiv">
    <script type="text/javascript">
      /* <![CDATA[ */
      var fastFoods = new Array();
      fastFoods[0] = "Pizza";
      fastFoods[1] = "Burgers";
      fastFoods[2] = "French Fries";
      fastFoods[3] = "Tacos";
      fastFoods[4] = "Burritos";
      fastFoods[5] = "Fried Chicken";
      fastFoods[6] = "Subs";
      for (var count = 0; count < fastFoods.length; count++)
      {
        document.write(fastFoods[count] + "<br/>");
      }
      /* ]]> */
    </script>
    <h3>This is a sample of a <i>for</i> statement.</h3>
  </div>
</body>
</html>
You can see the above code running here.

Please note these points about the above code:


Here is another sample of a for statement in action. We saw the array in this sample in Assignment 3. But in that assignment, the displayed numbers did not have trailing zeroes. This sample adds a for loop to add the trailing zeroes, and another for loop to display the array items.

<!doctype html>
<html>
<head>
  <meta charset="UTF-8">
  <link rel="stylesheet" type="text/css" href="Samples.css">
  <title>Interest Array with Formatting</title>
  <script type="text/javascript">
    /* <![CDATA[ */
    function formattedNumber(theNumber, lengthNeeded)
    {
      var numberStr = theNumber.toString();
      
      if (numberStr.length < lengthNeeded)
      {
        var numberZeroesNeeded = lengthNeeded - numberStr.length;
        for (var j = 0; j < numberZeroesNeeded; j++)
        {
          numberStr += "0";
        }
      }
      
      return numberStr;
    }
    
    var interestArray = new Array(7);
    
    interestArray[0] = .0725;
    interestArray[1] = .0750;
    interestArray[2] = .0775;
    interestArray[3] = .0800;
    interestArray[4] = .0825;
    interestArray[5] = .0850;
    interestArray[6] = .0875;
    /* ]]> */
  </script>
</head>
<body>
  <div id="mainDiv">
    <h3>The values in interestArray are:</h3>
    <script type="text/javascript">
      /* <![CDATA[ */
      for (var i = 0; i < interestArray.length; i++)
      {
        document.write(formattedNumber(interestArray[i], 6) + "<br />");
      }
      /* ]]> */
    </script>
  </div>
</body>
</html>
You can see the above code running here.

Please note these points about the above code:


Why Arrays?

You now know enough to more fully understand the answer to the question, "Why should we use arrays?" Here is some code that illustrates part of the answer:

<!doctype html>
<html>
<head>
  <meta charset="UTF-8">
  <link rel="stylesheet" type="text/css" href="Samples.css">
  <title>Why Arrays 2</title>
  <script type="text/javascript">
    /* <![CDATA[ */
    var actors = new Array();
    
    function writeTheActors()
    {
      var contentString = "";
      
      for (var i = 0; i < actors.length; i++)
      {
        contentString += actors[i] + "<br />";
      }
      
      document.getElementById("contentDiv").innerHTML = contentString;
    }

    function askForActors()
    {
      var keepGoing = true;
      var theActor;
      
      while (keepGoing)
      {
        theActor = prompt("Give me the name of one of your favorite actors/actresses, please.  Press Cancel or press Enter with nothing entered, when you are done.","");
        if ((theActor != null) && (theActor != ""))
        {
          actors[actors.length] = theActor;
        }
        else
        {
          keepGoing = false;
        }
      }
      
      writeTheActors();
    }
    /* ]]> */
  </script>
</head>

<body onload="askForActors();">
  <div id="mainDiv">
    <h3>Favorite Actors/Actresses</h3>

    <h4>Your favorites are:</h4>

    <div id="contentDiv"></div>
  </div>
</body>
</html>

You can see the "Why Arrays?" code running here.

Please note these points about the above code:

The last point in the above list mentions this feature of the document.write( ) built-in method: If document.write( ) is called after the page has completed loading, document.write( ) replaces the entire page contents, including all of the HTML tags. You can use this feature to re-write the page if you wish, beginning with the <html> tag, but this is a lot of work. It is usually better to replace the contents of a tag such as a <div>...</div> tag, using the innerHTML property. We will see this property again in future classes.


for...in Statements

Recall that the variables in an object are called properties.

The for...in statement is used to run some statements that do something with all of the properties within an object, one property at a time.

Here is the basic syntax for the for...in statement:

  for (variable in object)
  {
    statement;
    statement;
    ...
  }

Please note these points about the above syntax:

  1. The variable will hold an individual property name for each loop through the object's properties. The variable is created by JavaScript simply by its being in the for (variable in object) clause.
  2. The object name must be an object that exists (has been created -- either automatically by the browser, or by your code).
  3. No counter is needed. JavaScript automatically loops through all of the properties in the object, assigns each property to the variable one at a time, runs the statements (code block), and continues to the next property, etc.
  4. The for...in statement ends after the loop has handled the last property in the object.

Here is a sample of a for...in statement in action:

<!doctype html>
<html>
<head>
  <meta charset="UTF-8">
  <link rel="stylesheet" type="text/css" href="Samples.css">
  <title>For...In Loop</title>
</head>

<body>
  <div id="mainDiv">
    <h3>The properties in the window object are:</h3>
    <script type="text/javascript">
      /* <![CDATA[ */
      for (stuff in window)
      {
        document.write(stuff + "<br/>");
      }
      /* ]]> */
    </script>
  </div>
</body>
</html>
You can see the above code running here.

Please note these points about the above code:


Recall, please, that you can use a string as an array index in JavaScript. This kind of array is called an "Associative Array".

The values of the properties in an object are stored as an associative array in that object. What this means for our current purposes is that you can use the name of each object property as the index to that property's value in the array which is the list of properties in the object.

Here is a sample of using a for...in statement to display the value of each property of an object. This code is very similar to the code just above, but this time we are making use of the associative array which stores the values of the various properties:

<!doctype html>
<html>
<head>
  <meta charset="UTF-8">
  <link rel="stylesheet" type="text/css" href="Samples.css">
  <title>For...In Loop</title>
</head>

<body>
  <div id="mainDiv">
    <h3>The values of the properties in the window object are:</h3>
    <script type="text/javascript">
      /* <![CDATA[ */
      for (stuff in window)
      {
        document.write("The value of " + stuff + " is " + window[stuff] + "<br/>");
      }
      /* ]]> */
    </script>
  </div>
</body>
</html>
You can see the above code running here.


with Statements

Another statement that you can use to work with object properties (and methods) is the with statement. The with statement eliminates the need for you to type the name of the object over and over again in your code. When you put your statements that refer to an object's properties or methods within the code block of a with statement, you only have to type the name of the property or method.

Here is the basic syntax of the with statement:

  with (object)
  {
    statement;
    statement;
    ...
  }

Please note these points about the above syntax:

  1. The name of the object that you want to reference in the code block is placed within the parentheses.
  2. The statement(s) that will reference the object are placed within the curly braces.
  3. You only have to type the name of whatever property or method you are referring to, not the name of the object, in the code block.

Here is an example of how you can use the with statement to shorten your code (and save typing):

<!doctype html>
<html>
<head>
  <meta charset="UTF-8">
  <link rel="stylesheet" type="text/css" href="Samples.css">
  <title>With Statement</title>
</head>

<body>
  <div id="mainDiv">
    <script type="text/javascript">
      /* <![CDATA[ */
      with (document)
      {
        write("This is line 1.<br/>");
        write("This is line 2.<br/>");
        write("This is line 3.<br/>");
      }
      /* ]]> */
    </script>
  </div>
</body>
</html>

You can see the above code running here.

Please note these points about the above code:


Nested with Statements

It is possible to nest with statements. What this really means is that you can put a with statement inside another with statement.

Here is an example of how you can nest a with statement:

<!doctype html>
<html>
<head>
  <meta charset="UTF-8">
  <link rel="stylesheet" type="text/css" href="Samples.css">
  <title>Nested With Statement</title>
</head>

<body>
  <div id="mainDiv">
    <script type="text/javascript">
      /* <![CDATA[ */
      with (document)
      {
        with (window)
        {
          var winLeft = screenLeft ? screenLeft : screenX;
          var winTop = screenTop ? screenTop : screenY;

          write("location is " + location + "<br/>");
          write("screenLeft/screenX is " + winLeft + "<br/>");
          write("screenTop/screenY is " + winTop + "<br/>");
        }
      }
      /* ]]> */
    </script>
  </div>
</body>
</html>
You can see the above code running here.

Please note these points about the above code:


break and continue Statements

Recall that the break statement is used to stop the processing of a switch statement. The break statement may also be used to stop the processing of a while, do...while, for, and for...in statement. The break statement stops the execution of the switch or looping statement and tells JavaScript to run the next statement that follows the statement being halted.

The continue statement is used only with looping statements. It tells JavaScript to interrupt the processing of the loop, but then to go back to the top of the loop and start the next iteration.

Following are two versions of similar code. The first version uses a break statement inside a for loop, which stops the for loop completely. The second version uses a continue statement in a similar for loop, which interrupts the running of the current iteration but also starts another iteration of the loop and continues its processing:

<!doctype html>
<html>
<head>
  <meta charset="UTF-8">
  <link rel="stylesheet" type="text/css" href="Samples.css">
  <title>Break vs. Continue Statement</title>
</head>

<body>
  <div id="mainDiv">
    <h3>Results of <i>break</i>:</h3>
    <script type="text/javascript">
      /* <![CDATA[ */
      for (var count = 1; count <= 5; count++)
      {
        if (count == 3)
        {
          break;
        }
        document.write(count + "<br/>");
      }
      /* ]]> */
    </script>
    <h3>Results of <i>continue</i>:</h3>
    <script type="text/javascript">
      /* <![CDATA[ */
      for (var count = 1; count <= 5; count++)
      {
        if (count == 3)
        {
          continue;
        }
        document.write(count + "<br/>");
      }
      /* ]]> */
    </script>
  </div>
</body>
</html>
You can see the above code running here.

Please note these points about the above code: