Loops in JavaScript


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

Legal Disclaimer

Our website is not responsible for the information contained by this article. Webworldarticles.com is a free articles resource thus practically any visitor can submit an article. However if you notice any copyrighted material, please contact us and we will remove the article(s) in discussion right away.


This article was sent to us by: George Freedrich at 12272008

Related Articles

1. Nested Loops, label and continue Statements
The label statement does not inherently go with the continue statement but, like discussing break with switch and case, you mi...

2. Operators Precedence
The order in which expressions are evaluated based on their operators is known as precedence. Multiplication and division occur before addition and subtraction, so any op...

3. The ''with'' Statement
Like the ternary conditional operator, the with statement is a shortcut. Instead of having to list all of the properties of an object by repeating the basic objec...

4. Conditional Structures
The "thinking" structure in JavaScript is found in the different types of conditional statements in the language. Used in concert with different types of comparative oper...

5. Types of operators in JavaScript
Assignment Operators The key assignment operator is the equals sign (=). The left operand is a variable, an array element, or an objec...

6. JavaScript Lives in a Web Page
All the code that you write for JavaScript goes into an HTML page. If you don't know HTML yet, you should run out and get a good book on HTML. Lynda and William Weinman's...

7. JavaScript Literals
The raw data that make up the root of data types are called "literals." These are, in effect, literally what they represent themselves to be. Numbers, strings, and Boolea...

8. JavaScript Variables
I like to think of variables as containers on a container ship. You can put all different types of content into the containers, move them to another port, empty them, and...

9. JavaScript Operators
Operators can be placed into three categories-binary, unary, and ternary. Binary operators, most commonly associated with the concept of operator, take two (binary) expres...

10. JavaScript Arrays
Because objects are collections of properties with each property having its own name and value, arrays are actually JavaScript objects. Each property in an array is an el...