Loops in JavaScript

written by: George Freedrich; article published: year 2008, month 12;

In: Root » Computers and technology » AJAX and JavaScript » Loops in JavaScript

  Share  
|
  NL  |  FR  |  ES  |  PT  |  IT  |  DE  |  JP  |  CN  |  KR  |  RU  |  AE


Loops in JavaScript are similar to loops in C++ and Java and most other languages using loop structures. In this section, you will find explanations of the different types of loops in JavaScript and suggestions where they are typically used most effectively in a script.

The for Loop

One of the most used and familiar loops is the for loop. This loop iterates through a sequence of statements for a number of times determined by a condition. The condition can be a constant based on a numeric literal (a number) or a constant (that is, a math constant), or the loop can be variable depending on the count in the variable. The general format is shown here:

for(start value; termination condition; increment/decrement) {
      Statements 
      } 

The start value is the initial value of a counter variable. The first time through the loop, the counter value will be based on the start value. The termination condition is a test to determine whether the counter variable has met the condition that terminates the loop. The increment/decrement determines how much has been added or subtracted from the counter variable. A typical use for a loop is to examine characters in a string. The length of the string is used as the termination condition, and each character is based on its linear position in the string.

<html> 
<head> 
<title>For Loop</title> 
<script language="JavaScript"> 
var found = "Email address is missing @ symbol."; 
var emailAd=prompt("Please enter your email address:",""); 
for (var counter=0; counter <= emailAd.length; counter++) {
//The charAt(n) function looks at the character 'n' in the string 
            var findAt=emailAd.charAt(counter); 
                  if (findAt=="@") {
                              found="Email address has @ symbol"; 
                  } 
} 
document.write(found); 
</script> 
</head> 
<body bgColor="powderblue"> 
</body> 
</html>

Because the length of the string is a variable, the termination condition uses the length of the string rather than a literal value. In this particular example, all that the script is attempting to do is verify whether the user remembered to put in the "@" when she entered her email address.

The for/in Loop

A second format used with the for keyword in a loop is the for / in statement. When the for / in statement is used, the counter and termination are determined by the length of the object. The general format is shown here:

for (counter variable in object) {
      Statement 
} 

You do not need to know the number of properties in the object using for / in because the statement begins with 0 as the initial value of a counter variable and terminates the loop when all of the properties of the objects have been exhausted. For example, using an array object, the following loop begins with the first element of the array named airplane and keeps looping until no more elements are found in the array:

<html> 
<head> 
<title>For Loop</title> 
<script language="JavaScript"> 
var airFlock=""; 
var airplane = new Array("Cessna","Piper","Maule","Mooney","Boeing"); 
for (var counter in airplane) {
      airFlock += airplane[counter] + "<br>"; 
} 
document.write(airFlock); 
</script> 
</head> 
<body bgColor="powderblue"> 
</body> 
</html>

Because variables are objects in JavaScript, each character of a string variable is a property of the variable. Rewriting the script used to illustrate how a for loop works, the following for / in loop requires a simpler statement to arrive at the same results:

<html> 
<head> 
<title>Search For/In</title> 
<script language="JavaScript"> 
var complete="You are missing the @ character in your email address."; 
var emailAd = prompt("Enter your email address",""); 
for (var counter in emailAd) {
      if (emailAd[counter]=="@") {
            complete="You included your @ character."; 
      } 
} 
document.write(complete); 
</script> 
</head> 
<body bgColor="aliceblue"> 
</body> 
</html>

Using the for / in loop in simple strings is just as effective as its use in other objects that contain properties.

The while Loop

The while loop begins with a termination condition and keeps looping until the termination condition is met. The counter variable initialization and the counter increment/decrement are handled within the context of the while statement (that is, within the curly braces), but they are not part of the initial statement itself. The general format for the while loop is shown here:

initial value declaration 
while (termination condition) {
      statements 
      increment/decrement statement 
} 

As long as the termination condition is not met, the statements are executed and the counter variable increases or decreases in value. The following example illustrates the counter variable decrementing in steps of 5:

<html> 
<head> 
<title>While Loop</title> 
<script language="JavaScript"> 
var counter = 50; 
var teamGroups=""; 
while(counter > 0) {
      teamGroups +="Team " + counter + "<br>"; 
      counter -= 5; 
} 
document.write(teamGroups); 
</script> 
</head> 
<body bgColor="teal"> 
</body> 
</html>

The output to the screen is as shown:

Team 50 
Team 45 
Team 40 
Team 35 
Team 30 
Team 25 
Team 20 
Team 15 
Team 10 
Team 5

The fact that no Team 0 exists is important. As soon as the termination condition returned a Boolean false, the loop was immediately terminated and the script jumped over the statements within the loop and executed the next line. Had the termination condition been this, a Team 0 would have been included in the output:

while(counter >= 0) {

The do/while Loop

Unlike the while loop, the do / while loop always executes statements in the loop in the first iteration of the loop. Instead of the termination condition being at the top of the loop, it is at the bottom. The general format looks like the following:

do {
        statements 
        counter increment/decrement 
} while(termination condition) 

The keyword while is outside the curly braces beginning after the do keyword. Because arrays are commonly used with loops, the following shows a do / while loop extracting the properties of an array:

<html> 
<head> 
<title>Do/While Loop</title> 
<script language="JavaScript"> 
var bigCities= new Array("Beijing", "Tokyo", "Mexico City", "New York", "Los 
Angeles", "London", "Berlin", "Bloomfield") 
var counter=0; 
var metropolis=""; 
bigCities.sort( ); 
do {
      metropolis += bigCities[counter] + "<br>"; 
      counter++ 
} while (counter < bigCities.length) 
document.write(metropolis); 
</script> 
</head> 
<body bgColor="cornsilk"> 
</body> 
</html>

The sorting statement, bigCities.sort( ), puts the array elements into alphabetical order before the array is placed in the loop. Then the loop iterates until the counter variable returns a Boolean false based on the length of the array. Because the elements have been arranged alphabetically, the output is arranged alphabetically, as the following shows:

Beijing 
Berlin 
Bloomfield 
London 
Los Angeles 
Mexico City 
New York 
Tokyo

Share

Disclaimer

1) E-articles is not responsible for the information contained by this article as well for any and all copyright infringements by authors and writers. E-articles is a free information resource. If you suspect this article for any copyright infringement, please read the terms of service and contact us or use the "Report this article" button on this page to investigate the problem.
2) E-articles is not responsible for inaccuracies, falsehoods, or any other types of misinformation this article may contain and will not be liable for any loss or damage suffered by a user through the user's reliance on the information gained here.

link to this article