Home > Articles

This chapter is from the book

Loop Statements

Sometimes you will need to repeat an operation multiple times until a certain condition is true. As you will see in Chapter 5, "An Introduction to Arrays," this is especially important when you need to work with data stored in arrays. The types of statements used to accomplish repetitive loops are called loop statements. An integral part of these statements is comparison and increment operators discussed in Chapter 2.

There are three types of loop statements: the while statement, the do while statement, and the for statement. Let's look at the while statement first.

The while Statement

The while statement is the easiest of the looping statements to understand and use. Although it performs a different task, its structure is similar to the if statement:

while (expression) statement

or

while (expression)
 statement

Like all the looping statements, the first thing the while statement does is evaluate the expression contained within its parentheses to see whether the expression evaluates to true or false. If the expression evaluates to true, the while statement evaluates its statement(s). Where it differs from the statements that you have seen before is that it then goes back to recheck its expression. If the expression is true, then the JavaScript interpreter will execute the statement(s) in the statement block and it will evaluate the expression in parentheses again. The JavaScript interpreter will continue to loop in this way until the expression evaluates to false.

Clearly, if the while statement isn't to loop infinitely something in the expression has to change. This is achieved by including a variable in the expression that is changed by one of the statements evaluated by the loop during each evaluation. For example take a look at the following code:

var loopCounter = 0;

while (loopCounter <= 3)
 alert(loopCounter++);

This causes the display of four alert boxes in succession with the numbers 0, 1, 2 and 3 respectively. After the fourth alert has been displayed the variable loopCounter will contain a value of 4, so when the expression loopCounter <= 3 is evaluated, it returns false. Therefore, the while loop is not executed again and control passes to the statement that follows the while statement.

In Chapter 2 you learned that increment and decrement operators (++ and -- respectively) can be used to increment or decrement the value of their operand by 1. As you can see, this is especially useful in loops such as the one above. Every time the above alert is evaluated the value of the variable loopCounter is increased by 1. Therefore, after four loops the value of loopCounter is no longer less than or equal to three. Hence the expression evaluates to false, causing the while statement to stop looping, at which point evaluation will continue at the code following the while statement.

It is uncommon to actually use a long variable name such as loopCounter because they are extensively used in the statements belonging to the loop statement. It is standard practice to give counter variables the names i, j, and k so as to keep the code as uncluttered as possible. But note this is the only time that it is considered acceptable to give variables such nondescript names.

CAUTION

You must be careful that the variable in the expression changes each time so eventually it will cause the expression to evaluate to false. If you don't change the variable in the expression, the while statement will loop infinitely preventing any other scripts from running and, in some older browsers, will cause the browser to crash. This can happen if you forget to include a statement that increments/decrements the variable, or if you increment/decrement it in the wrong direction!

Generally, when you use the while statement you will want it to loop through more than just one line of code. To do this, include the curly braces as usual to create a statement block belonging to the while statement. For example, you could have written the above example like this:

var loopCounter = 0;
while (loopCounter <= 3) {
 alert(loopCounter);
 loopCounter++;
}

The do while Statement

The do while statement is very similar to the while statement. The difference is that the expression is evaluated at the end of the statement. In other words, the statement block is always evaluated once before the expression is evaluated. The structure of a do while statement is shown below:

do
 statement
while (expression);

The major effect of having the expression at the end of the loop is that the statements contained by the do while statement will be evaluated at least once before the expression is evaluated to decide whether it should loop again. For example try out the following code:

do
 alert("Statement evaluated!");
while (false);

As you will see, the alert box displays once regardless of the fact that the expression is simply the value false. Other than this, there is no difference between the way the while statement and the do while statement work.

If you want a do while statement to control multiple statements use a statement block, like this:

do {
 statement1
 statement2
 ...
 statement5
} while(condition);

CAUTION

Because the do while statement does not end with a closing curly brace, it requires a semicolon after the closing parenthesis. Forgetting to include the semicolon may cause an error.

The for Statement

The while and do...while statements have three essential elements: a statement that sets the initial value of a counter; an expression that tests a condition; and an expression that increments the counter. It can be easy to forget one or other of these when you are quickly typing out a piece of code, and you could end up with problems such as infinite loops. Fortunately, there is an alternative in the form of the for statement, which can contain all these elements in one place. It is written with the following structure:

for (setInitialCounterValue; testCondition; changeCounterValue)
 statement

Because all three of the essential parts of a loop statement are located between the parentheses, the for loop is much more popular than the other two methods because it is easier to follow the logic that controls the looping.

NOTE

The for statement can govern multiple statements by enclosing them in a statement block.

Here's a simple example that would display three alert boxes:

for (var i=0; i<3; i++) {
 alert(i);
}

The first statement in the parentheses declares and assigns to the variable i an initial value. It is this variable that then acts as the loop counter. Note that it is only evaluated at the beginning of the first loop. The second statement is the condition for the loop. Each time a loop finishes it is checked again to determine whether another loop should be made. Finally there is the third statement. It declares how the loop counter should be incremented (or decremented).

NOTE

Note that the three elements inside the parentheses are statements. Therefore, semicolons separate them and not commas. Remember this is how more than one statement can be placed on a single line.

CAUTION

The variable used for the loop counter in a for statement is inside the parentheses so it can only be incremented using the increment and decrement operators ++ and -- or the full syntax equivalent to increase the value of the loop counter.

To get some experience using the for statement, let's try to use it to create a page that will generate a simple multiplication table. First, we will ask a user which multiplication table he wants to see; then we will output the first 12 lines of that multiplication table in an alert box.

The first thing we will need to do is ask the user to enter the multiplication table that he wants. This can be done using a prompt box that assigns the value to a variable we will call multTable. See the following example:

var multTable = prompt("Please enter the table.", "");

What about generating the table? We could write out each of the 12 lines concatenating each one to a variable. But this would be very inefficient. A better way would be to use a loop statement. To do that let's choose the for statement.

For the moment, let's ignore the statement needed for the statement block and concentrate on the for statement itself. We probably want to start at 1 so this can be the initial value of our counter i, and we know when we want to stop once we get to 12. With this in mind our for loop will need to look something like this:

for (var i=1; i<=12; i++) {
 statement;
}

Okay, that's fairly easy so far, but what about the statement the for loop controls? Well, to help decide what it should look like, it is useful to take a look initially at the first few lines of a multiplication table. Let's take the 2 times table as an example:

1 x 2 = 2
2 x 2 = 4
3 x 2 = 6

Looking at the table, you can see that the first element of each line increments by 1. To recreate this with each iteration of the loop, you could quite easily use the counter i.

The next three characters are always the same. The x and the equal sign could be created simply by using two strings, but the number in between depends on which table the user asks for. It's not much of a problem though as that value can simply be found in the variable multTable. Let's take a look at how our statement looks so far:

i + " x " + multTable + " = "

We are just concatenating all the components of the line together. But how do we actually add the answer to the end? Well actually it isn't too hard if you think about it. What we have on the left-hand side of the equal sign is exactly what generates the answer: i multiplied by the variable multTable. This is all that is needed to finish the statement. Well, almost. We will also want to include a new line character to make sure each line of the table is actually displayed on a new line. This is done with the escaped character \n. Our statement now looks like this:

i+ " x " +multTable+ " = " +(i*multTable)+ "\n";

During each iteration through the for loop, you will need to concatenate the line to a variable, which builds up the table. Call this variable theTable and your completed statement will look like this:

theTable += i+ " x " +multTable+ " = " +(i*multTable)+ "\n";

With this statement in place within the loop, and an alert for theTable after the loop, a multiplication table will be generated. If you also store the entire piece of code within a function, it will allow users to request a different table as many times as they like. If you use a hyperlink to call the function, Listing 3.6 shows how your finished page might look:

Listing 3.6 Multiplication Table Generator (multTableGenerator.htm)

<html>
<head>
<title>Multiplication Table Generator</title>

<script language="javascript" type="text/javascript">
<!--

function generateTable()
{
   var multTable = prompt("Please enter the table.", "");
   var theTable = "";
   for (i=1; i<=12; i++) {
    theTable += i+ " x " +multTable+ " = " +(i*multTable)+ "\n";
   }
   alert(theTable);
}

//-->
</script>

</head>
<body>

<h1>Multiplication Table Generator</h1>

<a href="javascript:generateTable()">Create New Table</a>

</body>
</html>

Try it yourself.

Before you finish, it is worth mentioning that a statement that is related to the loop statements is the break statement. Remember that the break statement allows you to prematurely break out of conditional statements. There is a similar statement for the loop statements called the continue statement. However, rather than breaking out of the loop altogether and carrying on evaluation further down the page, it simply prevents evaluation of any remaining statements in the statement block. The loop continues to check the condition at the top of the loop to see whether it should loop again. Later in the book you will learn just how this can be useful.

The for in Statement

A second use of the for loop is to loop through the properties and child objects of an object. Objects are the JavaScript entities that allow you to apply these tools to making a difference to your Web pages, and to a certain extent the browser. (Objects will be covered in the next chapter.)

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