Home > Articles > Open Source > Ajax & JavaScript

This chapter is from the book

This chapter is from the book

6.3 Loops

Loops are used to execute a segment of code repeatedly until some condition is met. JavaScript's basic looping constructs are

  • while
  • for
  • do/while

6.3.1 The while Loop

The while statement executes its statement block as long as the expression after the while evaluates to true; that is, nonnull, nonzero, nonfalse. If the condition never changes and is true, the loop will iterate forever (infinite loop). If the condition is false, control goes to the statement right after the closing curly brace of the loop's statement block.

The break and continue functions are used for loop control.

Format

while (condition) {
  statements;
  increment/decrement counter;
}

Example 6.5.

  <html>
    <head>
      <title>Looping Constructs</title>
    </head>
    <body>
      <h2>While Loop</h2>
      <font size="+2">
1     <script type="text/javascript">
2       var i=0;    // Initialize loop counter
3       while ( i < 10 ){      // Test
4         document.writeln(i);
5         i++;    // Increment the counter
6       }    // End of loop block
7     </script>
      </font>
    </body>
  </html>

Explanation

  1. The JavaScript program starts here.
  2. The variable i is initialized to 0.
  3. The expression after the while is tested. If i is less than 10, the block in curly braces is entered and its statements are executed. If the expression evaluates to false, (i.e., i is not less than 10), the loop block exits and control goes to line 6.
  4. The value of i is displayed in the browser window (see Figure 6.4).
    Figure 6.4

    Figure 6.4 Output from Example 6.5.

  5. The value of i is incremented by 1. If this value never changes, the loop will never end.
  6. This curly brace marks the end of the while loop's block of statements.
  7. The JavaScript program ends here.

6.3.2 The do/while Loop

The do/while statement executes a block of statements repeatedly until a condition becomes false. Owing to its structure, this loop necessarily executes the statements in the body of the loop at least once before testing its expression, which is found at the bottom of the block. The do/while loop is supported in Mozilla/Firefox and Internet Explorer 4.0, JavaScript 1.2, and ECMAScript v3.

Format

do
   { statements;}
while (condition);

Example 6.6.

  <html>
    <head>
      <title>Looping Constructs</title>
    </head>
    <body>
      <h2>Do While Loop</h2>
      <font size="+2">
      <script type="text/javascript">
1       var i=0;
2       do{
3         document.writeln(i);
4         i++;
5       } while ( i < 10 )
      </script>
      </font>
    </body>
  </html>

Explanation

  1. The variable i is initialized to 0.
  2. The do block is entered. This block of statements will be executed before the while expression is tested. Even if the while expression proves to be false, this block will be executed the first time around.
  3. The value of i is displayed in the browser window (see Figure 6.5).
    Figure 6.5

    Figure 6.5 Output from Example 6.6, the do/while loop.

  4. The value of i is incremented by 1.
  5. Now, the while expression is tested to see if it evaluates to true (i.e., is i less than 10?). If so, control goes back to line 2 and the block is re-entered.

6.3.3 The for Loop

The for loop consists of the for keyword followed by three expressions separated by semicolons and enclosed within parentheses. Any or all of the expressions can be omitted, but the two semicolons cannot. The first expression is used to set the initial value of variables and is executed just once, the second expression is used to test whether the loop should continue or stop, and the third expression updates the loop variables; that is, it increments or decrements a counter, which will usually determine how many times the loop is repeated.

Format

for(Expression1;Expression2;Expression3)
  {statement(s);}
for (initialize; test; increment/decrement)
  {statement(s);}

The preceding format is equivalent to the following while statement:

Expression1;
while( Expression2 )
  { Block; Expression3};

Example 6.7.

  <html>
    <head>
      <title>Looping Constructs</title>
    </head>
    <body>
      <h2>For Loop</h2>
      <font size="+2">
      <script type="text/javascript">
1       for( var i = 0; i < 10; i++ ){
2         document.write(i);
3       }
      </script>
      </font>
    </body>
  </html>

Explanation

  1. 1 The for loop is entered. The expression starts with step 1, the initialization of the variable i to 0. This is the only time this step is executed. The second expression, step 2, tests to see if i is less than 10, and if it is, the statements after the opening curly brace are executed. When all statements in the block have been executed and the closing curly brace is reached, control goes back into the for expression to the last expression of the three. i is now incremented by one and the expression in step 2 is retested. If true, the block of statements is entered and executed.
  2. The value of i is displayed in the browser window (see Figure 6.6).
    Figure 6.6

    Figure 6.6 Output from Example 6.7.

  3. The closing curly brace marks the end of the for loop.

6.3.4 The for/in Loop

The for/in loop is like the for loop, except it is used with JavaScript objects. Instead of iterating the statements based on a looping condition, it operates on the properties of an object. This loop is discussed in Chapter 9, "JavaScript Core Objects," and is only mentioned here in passing, because it falls into the category of looping constructs.

6.3.5 Loop Control with break and continue

The control statements, break and continue, are used to either break out of a loop early or return to the testing condition early; that is, before reaching the closing curly brace of the block following the looping construct.

Table 6.1. Control Statements

Statement

What It Does

break

Exits the loop to the next statement after the closing curly brace of the loop's statement block.

continue

Sends loop control directly to the top of the loop and re-evaluates the loop condition. If the condition is true, enters the loop block.

Example 6.8.

  <html>
    <head>
      <title>Looping Constructs</title>
    </head>
    <body>
 1     <script type="text/javascript">
 2       while(true) {
 3         var grade=eval(prompt("What was your grade? ",""));
 4         if (grade < 0 || grade > 100) {
             alert("Illegal choice!");
 5           continue;   // Go back to the top of the loop
          }
          if(grade > 89 && grade < 101)
 6           {alert("Wow! You got an A!");}
 7        else if (grade > 79 && grade < 90)
            {alert("You got a B");}
          else if (grade > 69 && grade < 80)
            {alert("You got a C");}
          else if (grade > 59 && grade < 70)
            {alert("You got a D");}
 8        else {alert("Study harder. You Failed.");}
 9        answer=prompt("Do you want to enter another grade?","");
10        if(answer != "yes"){
11          break;    // Break out of the loop to line 12
          }
12      }
      </script>
    </body>
  </html>

Explanation

1

The JavaScript program starts here.

2

The while loop is entered. The loop expression will always evaluate to true, causing the body of the loop to be entered.

3

The user is prompted for a grade, which is assigned to the variable grade.

4

If the variable grade is less than 0 or more than 100, "Illegal choice" is printed.

5

The continue statement sends control back to line 2 and the loop is re-entered, prompting the user again for a grade.

6

If a valid grade was entered, and it is greater than 89 and less than 101, the grade "A" is displayed (see Figure 6.7).

7

Each else/if branch will be evaluated until one of them is true.

8

If none of the expressions are true, the else condition is reached and "You Failed" is displayed.

9

The user is prompted to see if he or she wants to enter another grade.

10, 11

If the answer is not yes, the break statement takes the user out of the loop, to line 12.

Figure 6.7

Figure 6.7 The user enters a grade, clicks OK, and gets another alert box.

6.3.6 Nested Loops and Labels

Nested Loops

A loop within a loop is a nested loop. A common use for nested loops is to display data in rows and columns. One loop handles the rows and the other handles the columns. The outside loop is initialized and tested, the inside loop then iterates completely through all of its cycles, and the outside loop starts again where it left off. The inside loop moves faster than the outside loop. Loops can be nested as deeply as you wish, but there are times when it is necessary to terminate the loop owing to some condition.

Example 6.9.

  <html>
    <head>
      <title>Nested loops</title>
    </head>
    <body>
      <script type="text/javascript">
        <!-- Hiding JavaScript from old browsers
1       var str = "@";
2       for ( var row = 0; row < 6; row++){
3         for ( var col=0; col < row; col++){
            document.write(str);
          }
4         document.write("<br />");
        }
        //-->
      </script>
    </body>
  </html>

Explanation

  1. The variable str is assigned a string "@".
  2. The outer for loop is entered. The variable row is initialized to 0. If the value of row is less than 6, the loop block (in curly braces) is entered (i.e., go to line 3).
  3. The inner for loop is entered. The variable col is initialized to 0. If the value of col is less than the value of row, the loop block is entered and an @ is displayed in the browser. Next, the value of col will be incremented by 1, tested, and if still less than the value of row, the loop block is entered, and another @ displayed. When this loop has completed, a row of @ symbols will be displayed, and the statements in the outer loop will start up again.
  4. When the inner loop has completed looping, this line is executed, producing a break in the rows (see Figure 6.8).
    Figure 6.8

    Figure 6.8 Nested loops: rows and columns. Output from Example 6.9.

Labels

Labels allow you to name control statements (while, do/while, for, for/in, and switch) so that you can refer to them by that name elsewhere in your program. They can be named the same as any other legal identifier that is not a reserved word. By themselves, labels do nothing. Labels are optional, but are often used to control the flow of a loop. A label looks like this, for example:

topOfLoop:

Normally, if you use loop-control statements such as break and continue, the control is directed to the innermost loop. There are times when it might be necessary to switch control to some outer loop. This is where labels most often come into play. By prefixing a loop with a label, you can control the flow of the program with break and continue statements as shown in Example 6.10. Labeling a loop is like giving the loop its own name.

Example 6.10.

  <script type="text/javascript">
1   outerLoop: for ( var row = 0; row < 10; row++){
2     for ( var col=0; col <= row; col++){
        document.write("row "+ row +"|column " + col, "<br /4");
3       if(col==3){
          document.write("Breaking out of outer loop at column
4              " + col +"<br />");
5         break outerLoop;
        }
      }
6     document.write("************<br />");
7   }    // end outer loop block
  </script>

Explanation

  1. The label outerLoop labels the for loop that follows it. It's like giving the for loop its own name so that it can be referenced by that name later.
  2. This is a nested for loop. As the program executes the row and column numbers are displayed.
  3. If the expression is true, the break statement, with the label, causes control to go to line 8; it breaks out of the outer: loop. A break statement without a label would cause the program to exit just the loop to which it belongs.
  4. The value of row and col are displayed as the inner loop iterates.
  5. The break statement with the label causes control to go to line 8.
  6. Each time the inner loop exits, this row of stars will be printed (see Figure 6.9).

    Figure 6.9

    Figure 6.9 Using a label with a loop.

    Notice that the row of stars is not printed when the loop is exited on line 5.

  7. The closing curly brace closes the outer for loop block on line 1.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020